aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib
diff options
context:
space:
mode:
Diffstat (limited to 'activemodel/lib')
-rw-r--r--activemodel/lib/active_model.rb4
-rw-r--r--activemodel/lib/active_model/serializers/json.rb38
2 files changed, 42 insertions, 0 deletions
diff --git a/activemodel/lib/active_model.rb b/activemodel/lib/active_model.rb
index 048f542239..544121c593 100644
--- a/activemodel/lib/active_model.rb
+++ b/activemodel/lib/active_model.rb
@@ -38,6 +38,10 @@ module ActiveModel
autoload :TestCase, 'active_model/test_case'
autoload :Validations, 'active_model/validations'
autoload :ValidationsRepairHelper, 'active_model/validations_repair_helper'
+
+ module Serializers
+ autoload :JSON, 'active_model/serializers/json'
+ end
end
I18n.load_path << File.dirname(__FILE__) + '/active_model/locale/en.yml'
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb
new file mode 100644
index 0000000000..60b5cbe948
--- /dev/null
+++ b/activemodel/lib/active_model/serializers/json.rb
@@ -0,0 +1,38 @@
+require 'active_support/json'
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/hash/slice'
+
+module ActiveModel
+ module Serializers
+ module JSON
+ extend ActiveSupport::Concern
+ include ActiveModel::Attributes
+
+ included do
+ cattr_accessor :include_root_in_json, :instance_writer => false
+ end
+
+ def encode_json(encoder)
+ options = encoder.options || {}
+
+ hash = if options[:only]
+ only = Array.wrap(options[:only]).map { |attr| attr.to_s }
+ attributes.slice(*only)
+ elsif options[:except]
+ except = Array.wrap(options[:except]).map { |attr| attr.to_s }
+ attributes.except(*except)
+ else
+ attributes
+ end
+
+ hash = { self.class.model_name.element => hash } if include_root_in_json
+ ActiveSupport::JSON.encode(hash)
+ end
+
+ def as_json(options = nil)
+ self
+ end
+ end
+ end
+end