Method: JsonObject::ClassMethods#object_accessor

Defined in:
lib/json_object.rb

#object_accessor(attribute, opts = {}) ⇒ Object

Similar to value_accessor.

Examples:

Accepting the default object class

object_accessor :address_information

Assigning a JsonObject class

object_accessor :address_information, class: AddressInformation

Parameters:

  • attribute (#to_s)

    will be used to retrieve the expected hash value from JsonObject#json_hash and will be the name of the new accessor method by default.

  • opts (Hash) (defaults to: {})

Options Hash (opts):

  • :name (#to_s)

    Will explicitly set the new accessor method name



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/json_object.rb', line 179

def object_accessor attribute, opts={}
  klass = opts.fetch(:class, JsonObject.default_json_object_class)
  set_parent = opts.fetch(:set_parent, true)
  create_value_accessor_method attribute, opts do |obj|
    value_for_attribute = obj.json_hash[attribute.to_s]
    methods_value = if value_for_attribute.is_a? Array
      value_for_attribute.inject([]) do |classes, hash|
        classes << klass.create(hash, set_parent ? obj : nil)
      end
    else
      value_for_attribute.nil? ? nil : klass.create(value_for_attribute, set_parent ? obj : nil)
    end
  end
  self
end