Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Model Serializer transform all dates to seconds

I need to convert all dates that get returned by my api into Unix date format (seconds). Individually is easy enough...

class ChimichangaSerializer < ActiveModel::Serializer
  attributes :updated_at,

  def updated_at
    object.updated_at.to_i
  end
end

But since I have to do it for everything, that way lies errors and madness. How can I achieve this functionality for all of them?

like image 636
TiggerToo Avatar asked Oct 15 '25 17:10

TiggerToo


1 Answers

Add the following:

app/config/initializers/time_with_zone.rb

class ActiveSupport::TimeWithZone
  def as_json(options = {})
    to_i
  end
end

this will override the default behaviour for all your timestamps when converted into json.

like image 75
coorasse Avatar answered Oct 18 '25 05:10

coorasse