Reputation: 2077
I have a Rails app that makes heavy use of the created_at
and updated_at
fields.
I've found that something like Post.last.created_at.to_f
will give me epoch time but I always need epoch time so I was wondering if there is some way to write an automated post-query filter that will do the conversion every time I called created_at
and update_at
. Right now, every time I read created_at
/updated_at
I repeat myself, which is bad form, and has already caused bugs when I forget to do the conversion.
I'm using Rails 3.2.13 and Ruby 1.9.3p392.
Also, I can't just write post.created_at.to_f
in my view since I'm using render JSON for my output.
Upvotes: 3
Views: 2046
Reputation: 972
Personally I believe approach suggested by @tadman is a better one.
created_at method can be as follows to do what you want:
def created_at
created_at= attributes["created_at"]
created_at ? created_at.to_f : nil
end
Place it in the models or attach it to ActiveRecord::Base. Carefully test it before putting to production.
Upvotes: 2
Reputation: 211590
Why don't you just make a method you can patch in to ActiveRecord::Base
?
def created_epoch
self.created_at.to_f
end
Then you won't have to remember to convert, you can just use that method instead.
Upvotes: 3