开发者

rails hash.as_json method producing unexpected result with boolean value

Ruby on Rails adds the "as_json" method to many common classes, which turns ActiveRecord objects into hash objects that can then be sent to a JSON serializer. Recently I encountered a bug in my code related to this method and it's treatment of boolean values.

I can summarize the bug very concisely:

{"foo" => true}.as_json

I would expect this method to return an identical hash. Instead, it returns

{"foo" => "true"}

This appears to be by design, as per line 157 in encoding.rb

AS_JSON = ActiveSupport::JSON::Variable.new('true').freeze

Can I ask, why is rails returning the string value "tr开发者_Python百科ue" instead of keeping it as a true boolean value?

My bug is as follows: I keep JSON-serialized objects in a cache. When I pull them out of the cache I leave them as hashes to avoid unnecessary object deserialization. If I don't find it in the cache, I pull the object out of the database and call as_json on it. I expect what I pull out of the cache and what I get back from as_json to be identical. They're not, because what comes out of the cache is {"foo" => true} and what comes back from as_json is {"foo" => "true"}


That's the way it's implemented.

You could change the default behavior putting this in an initializer:

class TrueClass
  def as_json(*options)
    self
  end
end

class FalseClass
  def as_json(*options)
    self
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜