如何教ActiveSupport不重写标准的"json“gem行为?
require "rubygems"
gem "json"
require "json"
class Time
def to_json(options = nil)
"custom string"
end
end
hash = { :x => Time.now }
puts hash.to_json # => {"x":custom string}
gem "activesupport"
require "active_support/core_ext/object" # Somewhere into Rails internals
puts Time.now.to_json # => custom string
puts hash.to_json # => {"x":"2011-02-14T16:30:10+05:00"}期望:在需要"active_support/core_ext/object“之后,我想得到{”x“:自定义字符串}结果。
发布于 2011-02-14 21:02:14
由于一些重要的原因,Rails从v2.3.3开始切换到#as_json。所以和它一起跳舞吧。
http://weblog.rubyonrails.org/2009/7/20/rails-2-3-3-touching-faster-json-bug-fixes
发布于 2011-02-14 19:47:20
你必须定义
class Time
def to_json(options = nil)
"custom string"
end
end之后
gem "activesupport"
require "active_support/core_ext/object" 代码。
发布于 2011-02-14 20:19:18
使用像Time.now.strftime("format")这样的strftime格式化Time.now值怎么样?对于格式化字符串,请参阅Ruby Docs。
或者,如果您不想格式化它,只需将其作为字符串调用Time.now.to_s即可
https://stackoverflow.com/questions/4991709
复制相似问题