Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serialize date attributes

I am using active_model_serializers and ember.js. One of my models has a date attribute. In rails date attributes are serialized in the format of "YYYY-MM-DD".

The problem; when ember-data de-serializes the date using the javascript Date constructor it assumes an "incorrect" timezone.

*Incorrect is not the best word but it is incorrect because I want it to default to the current timezone. DS.Model date attribute parses date (YYYY-MM-DD) incorrectly

I am thinking the active_model_serializer should take the date attribute and convert it to iso8601 format.

 Object.date.to_time_in_current_zone.iso8601

Is there a way to tell active_model_serializers how to serialize all date objects? Or should I be fixing the timezone issue in javascript?

like image 569
Aaron Renoir Avatar asked Sep 21 '12 21:09

Aaron Renoir


2 Answers

Here is my current solution but I really feel it should be possible to define how date objects get serialized globally.

class InvoiceSerializer < ActiveModel::Serializer
  attributes :id, :customer_id, :balance

  def attributes
    hash = super
    hash['date'] = object.date.to_time_in_current_zone.iso8601 if object.date
    hash
  end
end

UPDATE

My preferred solution now is to monkey patch the ActiveSupport::TimeWithZone.as_json method.

#config/initializers/time.rb
module ActiveSupport
  class TimeWithZone
    def as_json(options = nil)
      time.iso8601
    end
  end
end

class InvoiceSerializer < ActiveModel::Serializer
  attributes :id, :customer_id, :balance, :date
end
like image 194
Aaron Renoir Avatar answered Oct 30 '22 04:10

Aaron Renoir


In the last version of ActiveSupport (4.2) Dates are under iso8601 format. You don't need anymore Monkey Patch. You can configure the output format

#config/initializers/time.rb
ActiveSupport::JSON::Encoding.use_standard_json_time_format = true # iso8601 format
ActiveSupport::JSON::Encoding.time_precision = 3 # for millisecondes

See the doc

like image 21
Joel AZEMAR Avatar answered Oct 30 '22 04:10

Joel AZEMAR