如何教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”:自定义字符串}结果。
答案 0 :(得分:1)
由于某些重要原因,自v2.3.3转换为#as_json以来的Rails。所以和它一起跳舞。
http://weblog.rubyonrails.org/2009/7/20/rails-2-3-3-touching-faster-json-bug-fixes
答案 1 :(得分:0)
你必须定义
class Time
def to_json(options = nil)
"custom string"
end
end
之后
gem "activesupport"
require "active_support/core_ext/object"
码
答案 2 :(得分:0)
如何使用Time.now
strftime
格式化Time.now.strftime("format")
格式字符串Time.now.to_s
,请参阅Ruby Docs。
或者,如果您不想格式化它,只需将其用作字符串调用{{1}}