Module: Attribrutal::Model::ClassMethods

Defined in:
lib/attribrutal/model.rb

Instance Method Summary collapse

Instance Method Details

#attribute(sym, coercer = nil, attrs = {}) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/attribrutal/model.rb', line 33

def attribute (sym, coercer=nil, attrs = {})

  if coercer == Attribrutal::Type::Boolean
    superclass.send :define_method, "#{sym}?" do
      send(sym)
    end
  end

  superclass.send :define_method, sym do
    default_value = case attrs[:default].class.name
                    when "NilClass", "TrueClass", "FalseClass", "Numeric", "Fixnum", "Symbol"
                      attrs[:default]
                    when "Proc"
                      attrs[:default].call
                    else
                      attrs[:default].clone
                    end
    if coercer && coercer.respond_to?(:coerce)
      coercer.send(:coerce, raw_attributes[sym], default_value)
    else
      raw_attributes[sym] ||= default_value
    end
  end

  superclass.send :define_method, "#{sym}=".to_sym do |value|
    raw_attributes[sym] = value
  end

  if @attributes
    @attributes.merge!({ sym => coercer })
  else
    @attributes = { sym => coercer }
  end
end

#attribute_keysObject



72
73
74
# File 'lib/attribrutal/model.rb', line 72

def attribute_keys
  @attributes.keys
end

#attributesObject



68
69
70
# File 'lib/attribrutal/model.rb', line 68

def attributes
  @attributes
end