Method: CollectionJSON::Attribute.attribute

Defined in:
lib/collection-json/attribute.rb

.attribute(name, opts = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/collection-json/attribute.rb', line 13

def self.attribute(name, opts={})
  nested_attributes << name
  define_method(name) do |arg=nil|
    if arg != nil
      if opts[:transform]
        instance_variable_set(:"@#{name}", opts[:transform].call(arg))
      else
        instance_variable_set(:"@#{name}", arg)
      end
    else
      if instance_variable_get(:"@#{name}").nil? && opts[:default]
        instance_variable_set(:"@#{name}", opts[:default].dup)
       else
        instance_variable_get(:"@#{name}")
      end
    end
  end
  add_find_method(name, opts[:find_method]) if opts.has_key?(:find_method)
end