1

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?

Datt
  • 851
  • 9
  • 21

3 Answers3

1

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.

Datt
  • 851
  • 9
  • 21
0

Overriding to_json only changes the behavior when the TimeWithZone instance is serialized into JSON; however, as you've perhaps noticed, DelayedJob serializes into YAML. You can just tell Rails to use a default date/time format everywhere, though, with the methods from this thread. For example, add a file named config/initializers/datetime.rb with the contents:

Time::DATE_FORMATS[:default] = "%Y-%m-%d %H:%M:%S %z" 

Which will override the default format for every time a Time is converted to a string.

Community
  • 1
  • 1
Robert Nubel
  • 7,104
  • 1
  • 18
  • 30
  • I had tried that as well, but still returning in `2015-07-21 16:01:33 UTC` this format only – Datt Jul 29 '15 at 09:00
0

The problem stems from an inconsistent overriding of as_json that only applies to instances of TimeWithZone but does not effect the as_json monkey patching of Time, Date, and DateTime.

My tmp fix:

# config/initializers/time_with_zone.rb

module ActiveSupport
  class TimeWithZone
    def as_json(options = nil)
      iso8601
    end
  end
end
Viktor Ivliiev
  • 1,015
  • 4
  • 14
  • 21