Basically, I wanted to instantiate a Javascript Date object from a Ruby Date object via a JSON call. The problem is that Javascript's Date object constructor can't parse the default string output by Ruby's Date#to_s.
However, it can parse an integer which is milliseconds since the Unix epoch. Ruby's Date#to_i outputs the number of seconds since the unix epoch. So, using my mad arithmetic skillz, I figured I can create a Javascript Date with:
new Date(rubyGeneratedInteger * 1000);
So my usage of it went something like this. In my rails model, I generate an appropriate integer representation of the timestamp:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Order < ActiveRecord::Base | |
def queued_at_utc | |
queued_at.to_i | |
end | |
# ... | |
end |
I make that available to a JSON client through the controller:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class QueuedOrdersController < ApplicationController | |
def show | |
respond_to do |format| | |
format.json { | |
render :json=>@order.to_json( | |
:methods=>[:queued_at_utc] | |
# ... | |
) | |
} | |
end | |
end | |
end |
And consume it from the Javascript client thus:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Date.fromSecondsSinceEpoch = function(seconds) { | |
return new Date(seconds * 1000); | |
}; | |
// JSON call to retrieve queued order (using JQuery) | |
$.ajax({ | |
type: 'GET', | |
success: handleQueuedOrder, | |
url: 'http://localhost:3000/queued_orders/1', | |
dataType: 'json' | |
}); | |
function handleQueuedOrder(data) { | |
var order = data['queued_order']; | |
var queued_at = Date.fromSecondsSinceEpoch(order.queued_at_utc); | |
alert('Order queued at: ' + queued_at); | |
} |
No comments:
Post a Comment