在 rails 4 中反序列化时更改日期时间格式

Changing datetime formatting while deserilizing in rails 4

我正在使用 rails 4。我需要将全局日期时间格式设置为 "%Y-%m-%d %H:%M:%S %z",即 2015-07-29 02:34:38 +0530。 我试图覆盖有效的 as_json 方法,但是当我将它与 delayed_job 一起使用时,它是将日期时间字段转换为 2015-07-29 02:34:38 UTC 的序列化对象。

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

如果全局重写 serializable_hash 方法,它会起作用吗?如果可以,我该怎么办?

重写 to_json 仅更改 TimeWithZone 实例序列化为 JSON 时的行为;但是,您可能已经注意到,DelayedJob 序列化为 YAML。不过,您可以使用 this thread 中的方法告诉 Rails 在所有地方使用默认的 date/time 格式。例如,添加一个名为 config/initializers/datetime.rb 的文件,其内容为:

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

每次将时间转换为字符串时都会覆盖默认格式。

我已经通过重写 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 通过保存它的 typevalue 序列化对象的属性 因为时区对象类型是 ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter,其 deserialize 方法调用 convert_time_to_time_zone(value),通过覆盖它我得到了我想要的格式。

问题源于 as_json 的不一致重写,它仅适用于 TimeWithZone 的实例,但不影响时间、日期和日期时间的 as_json 猴子修补。

我的 tmp 修复:

# config/initializers/time_with_zone.rb

module ActiveSupport
  class TimeWithZone
    def as_json(options = nil)
      iso8601
    end
  end
end