Search code examples
ruby-on-railsrubyjsonserializationdelayed-job

Changing datetime formatting while deserilizing in rails 4


I'm using rails 4. I need to have a global datetime format to be set as "%Y-%m-%d %H:%M:%S %z" i.e. 2015-07-29 02:34:38 +0530. I tried to override as_json method which works but when I'm using it with delayed_job, It's serializing object which converts datetime field into 2015-07-29 02:34:38 UTC.

class ActiveSupport::TimeWithZone
  def as_json(options = {})
    strftime('%Y-%m-%d %H:%M:%S %z')
  end
end

Will it work if serializable_hash method overriden globally? If yes, how can I?


Solution

  • I have solved this problem by overriding TimeZoneCOnverter.

    module ActiveRecord
      module AttributeMethods
        module TimeZoneConversion
          class TimeZoneConverter
            def convert_time_to_time_zone(value)
              if value.is_a?(Array)
                value.map { |v| convert_time_to_time_zone(v) }
              elsif value.acts_like?(:time)
                # changed from value.in_time_zone to
                value.to_time
              else
                value
              end
            end
          end
        end
      end
    end
    

    delayed_job serializes the object's attributes by saving it's type and value for time zone object type is ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter whose deserialize method calls convert_time_to_time_zone(value), by overriding it I got format that I wanted.