Class: AsJson::JsonEncoder

Inherits:
Object
  • Object
show all
Defined in:
lib/as_json/json_encoder.rb

Instance Method Summary collapse

Constructor Details

#initialize(object, options) ⇒ JsonEncoder

Returns a new instance of JsonEncoder.



5
6
7
8
9
# File 'lib/as_json/json_encoder.rb', line 5

def initialize(object, options)
  @object = object
  @options = as_json_options(options)
  @subobject_attributes = {}
end

Instance Method Details

#jsonObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/as_json/json_encoder.rb', line 11

def json
  json = attributes_to_encode.map do |attribute, method|
    if attribute == method && @object.respond_to?(method)
      [clean_json_key(attribute.to_s), @object.send(method).as_json(subobjects_as_json_options(attribute))]
    else
      value = method.is_a?(Proc) ? @object.instance_exec(&method) : @object.send(method)
      [clean_json_key(attribute.to_s), value.as_json(subobjects_as_json_options)]
    end
  end.to_h

  json['id'] = @object.hashed_id if @object.respond_to?(:hashed_id) && json['id'].blank?
  json = json.sort_by { |k, _v| k == 'id' ? '_id' : k }.to_h
  json['_type'] = @object.class.name.underscore
  json.except(*[@options[:without] || []].flatten.map(&:to_s))
end