3

如何教 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"}

预期:在 require "active_support/core_ext/object" 之后我想得到 {"x":custom string} 结果。

4

3 回答 3

1

由于一些重要原因,自 v2.3.3 起的 Rails 切换到 #as_json。所以与它共舞。

http://weblog.rubyonrails.org/2009/7/20/rails-2-3-3-touching-faster-json-bug-fixes

于 2011-02-14T13:02:14.333 回答
0

你必须定义

class Time
  def to_json(options = nil)
    "custom string"
  end
end

gem "activesupport"
require "active_support/core_ext/object" 

代码。

于 2011-02-14T11:47:20.043 回答
0

如何使用格式化字符串格式化您的Time.now值,strftimeTime.now.strftime("format")参阅Ruby 文档

或者,如果您真的不想格式化它,只需将其用作字符串调用Time.now.to_s

于 2011-02-14T12:19:17.857 回答