提交 6e73cf6b 编写于 作者: J Jeremy Kemper

Fix AR json encoding

上级 99cf77be
......@@ -3,8 +3,9 @@ module Serialization
class Serializer #:nodoc:
attr_reader :options
def initialize(record, options = {})
@record, @options = record, options.dup
def initialize(record, options = nil)
@record = record
@options = options ? options.dup : {}
end
# To replicate the behavior in ActiveRecord#attributes,
......
require 'active_support/json'
require 'active_support/core_ext/module/model_naming'
module ActiveRecord #:nodoc:
module Serialization
......@@ -74,36 +75,17 @@ module Serialization
# "title": "Welcome to the weblog"},
# {"comments": [{"body": "Don't think too hard"}],
# "title": "So I was thinking"}]}
def to_json(options = {})
json = JsonSerializer.new(self, options).to_s
if include_root_in_json
"{#{self.class.json_class_name}:#{json}}"
else
json
end
def encode_json(encoder)
hash = Serializer.new(self, encoder.options).serializable_record
hash = { self.class.model_name.element => hash } if include_root_in_json
ActiveSupport::JSON.encode(hash)
end
def as_json(options = nil) self end #:nodoc:
def from_json(json)
self.attributes = ActiveSupport::JSON.decode(json)
self
end
private
# For compatibility with ActiveSupport::JSON.encode
def rails_to_json(options, *args)
to_json(options)
end
class JsonSerializer < ActiveRecord::Serialization::Serializer #:nodoc:
def serialize
ActiveSupport::JSON.encode(serializable_record)
end
end
module ClassMethods
def json_class_name
@json_class_name ||= name.demodulize.underscore.inspect
end
end
end
end
......@@ -170,18 +170,18 @@ def @david.favorite_quote; "Constraints are liberating"; end
def test_should_allow_only_option_for_list_of_authors
authors = [@david, @mary]
assert_equal %([{"name":"David"},{"name":"Mary"}]), authors.to_json(:only => :name)
assert_equal %([{"name":"David"},{"name":"Mary"}]), ActiveSupport::JSON.encode(authors, :only => :name)
end
def test_should_allow_except_option_for_list_of_authors
authors = [@david, @mary]
assert_equal %([{"id":1},{"id":2}]), authors.to_json(:except => [:name, :author_address_id, :author_address_extra_id])
assert_equal %([{"id":1},{"id":2}]), ActiveSupport::JSON.encode(authors, :except => [:name, :author_address_id, :author_address_extra_id])
end
def test_should_allow_includes_for_list_of_authors
authors = [@david, @mary]
json = authors.to_json(
json = ActiveSupport::JSON.encode(authors,
:only => :name,
:include => {
:posts => { :only => :id }
......@@ -200,6 +200,6 @@ def test_should_allow_options_for_hash_of_authors
2 => @mary
}
assert_equal %({"1":{"name":"David"}}), authors_hash.to_json(:only => [1, :name])
assert_equal %({"1":{"name":"David"}}), ActiveSupport::JSON.encode(authors_hash, :only => [1, :name])
end
end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册