aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib/active_model/serializers/json.rb
blob: 60b5cbe94849cd489d61918651c88291826c728e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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