Search code examples
ruby-on-railsrubyactive-model-serializers

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?


Solution

  • After seeing your comment regarding input conversion as well, I think you could override the getter and setter methods for those fields if you're not using them in any other form. Maybe something along these lines would help.

    It's important to note that this will affect not only the field's serialization. If you want to keep normal behaviour for those fields, I'd go with Tadman's advise.

    # with_unix_time.rb
    module WithUnixTime
      # These methods lack error handling
      def to_unix_time(*fields)
        fields.each do |field|
    
          # Override getter.
          define_method field do
            self[field].to_i
          end
    
          # Override setter
          define_method "#{field}=" do |value|
            self[field] = Time.at(value)
          end
    
          # Convenience method to retrieve the original DateTime type
          define_method "raw_#{field}" do
            self[field]
          end
        end
      end
    end
    
    # chimichanga.rb
    class Chimichanga < ActiveRecord::Base
      extend WithUnixTime
      to_unix_time :time_to_kill, :time_for_joke
    end