Module: JSONConvertible::InstanceMethods

Defined in:
lib/json_convertible.rb

Overview

add these as instance methods

Instance Method Summary collapse

Instance Method Details

#to_json(options = {}) ⇒ Object



16
17
18
# File 'lib/json_convertible.rb', line 16

def to_json(options = {})
  to_object_dictionary.to_json(options)
end

#to_object_dictionary(ignore_instance_variables: []) ⇒ Object

@ignore_instance_variables: optional to provide a list of

variables to attributes to ignore
@example

  ignore_instance_variables: [:@project, :@something_else]


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/json_convertible.rb', line 26

def to_object_dictionary(ignore_instance_variables: [])
  object_hash = {}
  instance_variables.each do |var|
    next if ignore_instance_variables.include?(var)

    # If we encounter with a `var` which value is an `Array`, we should iterate
    # over its value and use its own `to_object_dictionary`.
    if instance_variable_get(var).kind_of?(Array)
      object_array = []
      instance_variable_get(var).each do |obj|
        # If the `Array` type does not include the JSONConvertible mixin, don't
        # call `to_object_dictionary` on the elements, since the method does not exist
        if obj.class.include?(JSONConvertible)
          object_array << obj.to_object_dictionary
        else
          object_array << obj
        end
      end
      # In this step we have all the objects, lastly we need the key of the array.
      var_name, = _to_object_dictionary(var)
      object_hash[var_name] = object_array
    else
      var_name, instance_variable_value = _to_object_dictionary(var)
      object_hash[var_name] = instance_variable_value
    end
  end
  return object_hash
end