From a03097759bd7103bb9db253e7ba095f011453f75 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Sat, 5 Jul 2014 14:23:01 -0700 Subject: Merge pull request #16059 from jenncoop/json-serialized-attr Fixed issue with ActiveRecord serialize object as JSON Conflicts: activerecord/CHANGELOG.md activerecord/lib/active_record/attribute_methods/serialization.rb --- activerecord/lib/active_record.rb | 1 + .../lib/active_record/attribute_methods/serialization.rb | 7 ++++++- activerecord/lib/active_record/coders/json.rb | 13 +++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 activerecord/lib/active_record/coders/json.rb (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index 17b00bbaea..9028970a3d 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -97,6 +97,7 @@ module ActiveRecord module Coders autoload :YAMLColumn, 'active_record/coders/yaml_column' + autoload :JSON, 'active_record/coders/json' end module AttributeMethods diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb index 734d94865a..264ce2bdfa 100644 --- a/activerecord/lib/active_record/attribute_methods/serialization.rb +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -37,7 +37,12 @@ module ActiveRecord # serialize :preferences, Hash # end def serialize(attr_name, class_name_or_coder = Object) - coder = if [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) } + # When ::JSON is used, force it to go through the Active Support JSON encoder + # to ensure special objects (e.g. Active Record models) are dumped correctly + # using the #as_json hook. + coder = if class_name_or_coder == ::JSON + Coders::JSON + elsif [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) } class_name_or_coder else Coders::YAMLColumn.new(class_name_or_coder) diff --git a/activerecord/lib/active_record/coders/json.rb b/activerecord/lib/active_record/coders/json.rb new file mode 100644 index 0000000000..0f60b6dab2 --- /dev/null +++ b/activerecord/lib/active_record/coders/json.rb @@ -0,0 +1,13 @@ +module ActiveRecord + module Coders # :nodoc: + class JSON # :nodoc: + def self.dump(obj) + ActiveSupport::JSON.encode(obj) + end + + def self.load(json) + ActiveSupport::JSON.decode(json) + end + end + end +end -- cgit v1.2.3