问题
I have some active record models which have a "published_on" attribute. When I attempt to cache models with a published_on date prior to 1/1/1900, I get an error such as:
Marshalling error for key 'popular_products': year too big to marshal: 1300 UTC
You are trying to cache a Ruby object which cannot be serialized to memcached.
I can reproduce a similar error with ruby:
irb(main)> Marshal.dump( Time.parse("1/1/1900") )
ArgumentError: year too big to marshal: 1899 UTC
What's the right approach for caching models with dates prior to 1900?
回答1:
As @j03w commented, this is a limitation of the Time type. I chose to change the type to Date, which resolved the problem.
回答2:
You can also overload the _dump and _load methods of Time class, as follow:
require 'time' # Time extension to have xmlschema method
class Time
def _dump(level)
xmlschema(9) # store nsec
end
def self._load(str)
Time.parse(str)
end
end
irb(main):013:0> t=Time.new(1515,1,1)
=> 1515-01-01 00:00:00 +0100
irb(main):014:0> a=Marshal.dump(t)
=> "\x04\bIu:\tTime(1515-01-01T00:00:00.000000000+01:00\x06:\x06ET"
irb(main):015:0> t==Marshal.load(a)
=> true
来源:https://stackoverflow.com/questions/18247465/marshalling-error-when-caching-models-with-date-prior-to-1900