module Attribrutal::Model::ClassMethods

Public Instance Methods

attribute(sym, coercer=nil, attrs = {}) click to toggle source
# 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_keys() click to toggle source
# File lib/attribrutal/model.rb, line 72
def attribute_keys
  @attributes.keys
end
attributes() click to toggle source
# File lib/attribrutal/model.rb, line 68
def attributes
  @attributes
end