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

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

Ruby Docsを参照しTime.nowstrftimeください。Time.now.strftime("format")

または、本当にフォーマットしたくない場合は、文字列呼び出しとして使用してくださいTime.now.to_s

于 2011-02-14T12:19:17.857 に答える