Class: AsJson::JsonEncoder
- Inherits:
-
Object
- Object
- AsJson::JsonEncoder
- Defined in:
- lib/as_json/json_encoder.rb
Instance Method Summary collapse
-
#initialize(object, options) ⇒ JsonEncoder
constructor
A new instance of JsonEncoder.
- #json ⇒ Object
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, ) @object = object @options = () @subobject_attributes = {} end |
Instance Method Details
#json ⇒ Object
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((attribute))] else value = method.is_a?(Proc) ? @object.instance_exec(&method) : @object.send(method) [clean_json_key(attribute.to_s), value.as_json()] 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 |