module JSONConvertible::InstanceMethods
add these as instance methods
Public Instance Methods
to_json(options = {})
click to toggle source
# File lib/json_convertible.rb, line 16 def to_json(options = {}) to_object_dictionary.to_json(options) end
to_object_dictionary(ignore_instance_variables: [])
click to toggle source
@ignore_instance_variables: optional to provide a list of
variables to attributes to ignore @example ignore_instance_variables: [:@project, :@something_else]
# 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
Protected Instance Methods
_to_object_dictionary(var)
click to toggle source
# File lib/json_convertible.rb, line 57 def _to_object_dictionary(var) # For a given object variable we check if it includes some custom value mapping to JSON. if self.class.attribute_name_to_json_proc_map.key?(var) instance_variable_value = self.class.attribute_name_to_json_proc_map[var].call(instance_variable_get(var)) else instance_variable_value = instance_variable_get(var) end # For a given object variable we check if it includes some custom property mapping to JSON if self.class.attribute_key_name_map.key?(var) var_name = self.class.attribute_key_name_map[var] else var_name = var.to_s[1..-1] end return var_name, instance_variable_value end