serialize date attributes
-
03-07-2021 - |
Pergunta
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?
Solução
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
Outras dicas
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