Module: Chimera::Attributes::ClassMethods

Defined in:
lib/chimera/attributes.rb

Instance Method Summary collapse

Instance Method Details

#attribute(name, type = nil, extra_opts = {}) ⇒ Object

available types include: model



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/chimera/attributes.rb', line 14

def attribute(name, type = nil, extra_opts={})
  @defined_attributes ||= {}
  @defined_attributes[name.to_sym] = [type, extra_opts]
  define_method("#{name}") do
    return nil unless @attributes
    if type == :model
      @cached_attributes ||= {}
      @cached_attributes[name.to_sym] ||= begin
        model_id = @attributes[name.to_sym]
        klass = extra_opts[:class]
        if model_id && klass
          eval(klass.to_s.camelize).find(model_id)
        end
      end
    else
      @attributes[name.to_sym]
    end
  end
  define_method("#{name}=") do |val|
    return nil unless @attributes
    if type == :model
      @cached_attributes ||= {}
      @cached_attributes.delete(name.to_sym)
      if val.respond_to?(:id)
        @attributes[name.to_sym] = val.id
      else
        @attributes.delete(name.to_sym)
      end
    else @attributes
      @attributes[name.to_sym] = val
    end
  end
end

#defined_attributesObject



9
10
11
# File 'lib/chimera/attributes.rb', line 9

def defined_attributes
  @defined_attributes || {}
end