Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/active_support/json/encoding/active_support_encoder.rb

Instance Method Summary collapse

Instance Method Details

#as_json(options = nil) ⇒ Object

:nodoc:



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/active_support/json/encoding/active_support_encoder.rb', line 183

def as_json(options = nil) #:nodoc:
  # create a subset of the hash by applying :only or :except
  subset = if options
    if attrs = options[:only]
      slice(*Array(attrs))
    elsif attrs = options[:except]
      except(*Array(attrs))
    else
      self
    end
  else
    self
  end

  # use encoder as a proxy to call as_json on all values in the subset, to protect from circular references
  encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::ActiveSupportEncoder.new(options)
  Hash[subset.map { |k, v| [k.to_s, encoder.as_json(v, options)] }]
end

#encode_json(encoder) ⇒ Object

:nodoc:



202
203
204
205
206
207
208
209
210
# File 'lib/active_support/json/encoding/active_support_encoder.rb', line 202

def encode_json(encoder) #:nodoc:
  # values are encoded with use_options = false, because we don't want hash representations from ActiveModel to be
  # processed once again with as_json with options, as this could cause unexpected results (i.e. missing fields);

  # on the other hand, we need to run as_json on the elements, because the model representation may contain fields
  # like Time/Date in their original (not jsonified) form, etc.

  "{#{map { |k,v| "#{encoder.encode(k.to_s)}:#{encoder.encode(v, false)}" } * ','}}"
end