Module: Ecfr::AttributeMethodDefinition::ClassMethods

Defined in:
lib/ecfr/attribute_method_definition.rb

Instance Method Summary collapse

Instance Method Details

#attribute(attr, options = {}) ⇒ Object

Note:

If no type option is provided, String, is assumed by

Provides attribute definition. The attribute defined is expected to be part of the response. If the key in the response is different than the attribute name (eg you want to rename it) then the ‘value_key` option can be used.

When the :type option is :boolean we also define a predicate method (eg: we define both foo and foo?)

Class when it is instantiated (when :type is a class)

the YARD documentation generated. Types other than String are expected to be explicitely defined.

Parameters:

  • attr (<Symbol>)

    name of the attribute to define

  • options (<Hash>) (defaults to: {})

Options Hash (options):

  • type (<Symbol, Class>)

    a type to cast the JSON parsed value to. See Ecfr::AttributeCaster.

  • desc (<String>)
  • value_key (<String>)

    the name of the key in the repsonse (only needed if the attribute name is different than the key in the response)

  • options (<Hash>)

    options to be passed to



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ecfr/attribute_method_definition.rb', line 32

def attribute(attr, options = {})
  define_method attr do
    val = extract_value(attr, options)

    # sideloaded classes need their referrer to properly
    # cache themselves
    if options[:options] && options[:options][:self]
      options[:options][:referrer] = self
    end

    Ecfr::AttributeCaster.cast_attr(val, options[:type], options[:options] || {})
  end

  if options[:type] == :boolean
    define_method "#{attr}?" do
      val = extract_value(attr, options)
      Ecfr::AttributeCaster.cast_attr(val, options[:type], options[:options] || {})
    end
  end
end