I need to produce a date in Rails which looks like this:
/Date(1294268400000)/
I have tried various combinations of DateTime, to_i, to_json but never managed to get the /Date()/ thing.
Do I have to simply get my date in ms and then wrap the /Date(and )/ manually, or is there a built in method?
What about (ruby 1.9.x)?:
Time.now.strftime("/Date(%s%L)/")
=> "/Date(1335280866211)/"
You should try
new Date(posixMillisecondsHere)
first. MDN says that calling the Date function outside of the constructor context (i.e., without the new) will always return a string containing a formatted date rather than a Date object.
Strictly speaking, when you do that, you are writing JavaScript and not JSON. JSON cannot contain Date objects.
RFC 4627 says
2.1. Values
A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:
false null true
If you want to put a Date into what is strictly considered JSON and then get it back out, you must choose some way of using the JSON primitives (to wit, objects, arrays, numbers, strings, etc.) to encode a Date.
If you want to get a Date back out of JSON, whatever parses your JSON must understand the convention that you used to encode the Date.
Hope these are credible and/or official enough to help.
What about something like this:
in your config/en.yml file:
en:
time:
formats:
json: "/Date(%s%L)/"
and than in the view:
<%= l(Time.now, :format => :json) %>
Please note that you would need access to the helpers in the method that renders json. So it won't work if you are using ActiveRecord#to_json method for generating jsons.
Check out this question:
c# serialized JSON date to ruby
... simple answer seems to be to create a parse_date method.
It's the UNIX Epoch (seconds since 1970-01-01) right? What about using DateTime#strftime method?
# Taken from the Ruby documentation
seconds_since_1970 = your_date.strftime("%s")
UPDATE: OK, it's milliseconds, according to the documentation you can use your_date.strftime("%Q") to get the ms (but I've not tried yet).
Related
When notification is passed to the app after payumoney processing it sends response hash and we need to compute the hash and match it with the passed in response hash.
I use the following code to compute the expected response hash.
Digest::SHA512.hexdigest([
PAYU_SALT,
notification.transaction_status,
notification.user_defined,
notification.customer_email,
notification.customer_first_name,
notification.product_info,
notification.gross,
notification.invoice,
PAYU_KEY].join("|"))
The hash of the following string is computed
"salt|success|||||||||||||Payment|100.0|1|key"
When I print the following hash it gives
Digest::SHA512.hexdigest([
PAYU_SALT,
notification.transaction_status,
notification.user_defined,
notification.customer_email,
notification.customer_first_name,
notification.product_info,
notification.gross,
notification.invoice,
PAYU_KEY].join("|"))
#⇒ e7b3c5ba00b98aad9186a5e6eea65028a[...]
whereas notification.checksum gives
#⇒ 546f5d23e0cadad2d4158911ef72f095d[...]
So the two hashes don’t match.
I am using the following gem: https://github.com/payu-india/payuindia
I appreciate any help as to why the response hash is not matching. Is there any error in my logic to compute the response hash? Thanks!
Where did you come up with that order for the fields in the array?
Looking at PayU's Developer FAQ it seems like the order is the following:
key|txnid|amount|productinfo|firstname|email|||||||||||salt
Please make sure that the hash is calculated in the following format - hashSequence= key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5||||||salt
Please make sure that in the above sequence please use the UDFs which have also been posted to our server. In case you haven't posted any UDFs, the hash sequence should look like this - hashSequence= key|txnid|amount|productinfo|firstname|email|||||||||||salt.
Keep in mind that when computing the hash even a single character out of place will result in a completely different checksum.
little late but Actual Sequence is:
SALT|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key
Thanks to Ravi Kant Singh
but additionalCharges| are removed
Tested with live environment
Check your hash in above order and if its match you can process request
ok this was a silly mistake i made. The reason the hash didn't match was beacuse i had a typo with the PAYU test key. At the end i typed small 'u' when it was 'U'. The library is fine and the logic is right. The error was in my side with using wrong key.
Actual Sequence for hash is :
additionalCharges|SALT|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key
Actual hash generation for additional charges:
additionalCharges|SALT|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key
Without additional charges:
SALT|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key
In rails I have DateTime object as:
2014-08-21 18:14:12 UTC
I want to display it as:
08-21-2014
I can hack this as follows:
"2014-08-21 18:14:12 UTC".to_s.sub(/(\d*)(-)(\d*-\d*)/, '\3\2\1').first(10)
But I prefer the proper Rails/ Ruby way and not having to convert the Date object to a string. Thanks!
See DateTime#strftime:
> DateTime.now.strftime '%m-%d-%Y'
=> "08-22-2014"
And please, please, please don’t use that format, unless you have no choice. Hyphens should only be used for the Y-m-d format. Use slashes or dots if possible. (Even better, use Y-m-d!)
Just use strftime to get various formats of date & time.
> DateTime.now.strftime("%m-%d-%Y")
=> "08-23-2014"
Read more about strftime
How do I pass array of parameters through Get method in rails? Currently my URL loocs like this:
http://localhost:3000/jobs/1017/editing_job_suites/1017/editing_member_jobs/new?ids[]=1025&ids[]=1027
How can I pass the array with Get method but avoid ?ids[]=1025&ids[]=1027 part.
Request is being sent with javascript window.open method. Is there any workaround to send not ajax Post request.
You should stick to using a GET request if you are not changing the state of anything, and all you want to to access a read only value.
To send an array of ids to rails in a GET request simply name your variable with square brackets at the end.
//angular snippet
$http.(method:'GET',
...
params: {'channel_id':2, 'product_ids[]': productIds}
//where productIds is an array of integers
...
)
Do not concatenate your ids as a comma separated list, just pass them individually redundantly. So in the url it would look something like this:
?channel_id=2&product_ids[]=6900&product_ids[]=6901
url encoded it will actually be more like this:
?channel_id=2&product_ids%5B%5D=6900&product_ids%5B%5D=6901
Rails will separate this back out for you.
Parameters: {"channel_id"=>"2", "product_ids"=>["6900", "6901"]}
No, GET can only put variables on the url itself. If you want the URL to be shorter, you have to POST. That's a limitation feature of HTTP, not Rails.
I recently wanted to do this and found a workaround that is a little less complex, and so has some complexity limitations but may also be easier to implement. Can't speak to security, etc.
If you pass your array values as a string with a delimiter, e.g.
http://example.com/controller?job_ids=2342,2354,25245
Then you can take the result and parse it back to what you want:
job_ids = params[:job_ids].split(',')
Then do whatever:
job_ids.each do |job_id|
job = Job.find(job_id.to_i)
end
etc
#Homan answer is valid for using an external client (e.g curl or angular). Inside Rails test cases though, you should not use []. Here's an example:
get get_test_cases_url(**path_params), params: {case_ids: ["NON-9450", "NON-12345", "NON-9361"]}
This is using new format where get_test_cases is name of route and you pass to the method all params needed to construct the URL path. Query params are a separate hash.
FYI if I use [] like case_ids[], then instead of ["NON-9450", "NON-12345", "NON-9361"] I'm getting it parsed to [["NON-9450"], ["NON-12345"], ["NON-9361"]]
I am new to ruby on rails. I have passed parameters ISDCode,AreaCode and Telephone number using POST from a form.
I have a string with information of the format countryName(ISDCode) passed in the variable ISDCode. For example "United States of America(+1)".
Now I want to save only the value of the ISDCode in the database.
What would be the ideal way to extract the ISD Code from the string?
Should I extract the ISD Code in Javascript before user POSTs the form or should I extract it in the model using a callback ?
Also is regex the only way to extract the information?
Since the string is from auto completion, the ISDcodes should be existing in your database. So the best solution may be including an extra parameter (with a hidden input), like isdcode_id, then you simply use isdcode_id in your model. This way you can avoid the trouble to parse the string.
If this is not feasible, regex could be the best way to extract the information. You can override the setter in the model to do it.
use regular expression to match ISDcode
"United States of America(+1)" =~ /(\+[\d]+)/
puts $1
If you are interested in getting just the ISD Code alone, this should work:
"United States of America(+1)".gsub!(/[^\+\d]/, "")
NB: You can have this in your view helper and just call the helper on the string before persistence
Already answered, but I'd like to offer an alternative to getting the ISD Code:
isd = "United States(+1)"
puts isd[/[+]*[\d]{1,4}/] # +1
This regexp matches:
0001
+1
+01
etc.
I prefer to use js to extract information in the client side and make a validation in the model. By this way, you can get what you want and make sure it's correct.
I'm POSTing json data to a Grails controller which I then parse using JSON.parse.
It all works fine except for date fields. I don't believe there is an explicit syntax in json to represent a Date but I've tried a number of formats with no luck. Can anyone tell me what format I should use so that the grails JSON parser can create a Date object.
There isn't a specific format, but you can define your own. For example, these guys here are adding a '#' to the beginning and the end of the string.
According to Grails docs here, you can define:
grails.converters.json.date (String) - Configure how Date values
are serialized to JSON
"default" - String representation according to the JSON specification
"javascript" - new Date(...)
Update: It appears that there is no mapping to Java Date objects. If you know the fields that are dates, you can parse them into Dates