Module: Tableless::ClassMethods

Included in:
ActiveRecord::TablelessModel
Defined in:
lib/tableless_model/class_methods.rb

Instance Method Summary collapse

Instance Method Details

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

Macro to define an attribute of the Tableless model. To be used as follows in a tableless model:

class Example < ActiveRecord::TablelessModel

  attribute :name,    :type => :string
  attribute :active,  :type => :boolean, :default => true

end


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/tableless_model/class_methods.rb', line 17

def attribute(name, options = {})
  attribute_name = name.to_s

  # Defining the new attribute for the tableless model
  self.attributes[name] = options

  # Defining method-like getter and setter for the new attribute
  # so it can be used like a regular object's property
  class_eval %Q{
    def #{attribute_name}
      self[:#{attribute_name}]
    end

    def #{attribute_name}=(value)
      self[:#{attribute_name}] = value
    end
  }
end

#cast(attribute_name, value) ⇒ Object

If a data type has been specified for an attribute, its value will be converted accordingly (if necessary) when getting or setting it



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/tableless_model/class_methods.rb', line 54

def cast(attribute_name, value)
  type = self.attributes[attribute_name][:type] || :string

  return nil if value.nil? && ![:string, :integer, :boolean, :float, :decimal].include?(type)

  begin
    case type
      when :string    then (value.is_a?(String) ? value : String(value))
      when :integer   then (value.is_a?(Integer) ? value : value.to_s.to_i)
      when :float     then (value.is_a?(Float) ? value : value.to_s.to_f)
      when :decimal   then (value.is_a?(BigDecimal) ? value : BigDecimal(value.to_s))
      when :time      then (value.is_a?(Time) ? value : Time.parse(value))
      when :date      then (value.is_a?(Date) ? value : Date.parse(value))
      when :datetime  then (value.is_a?(DateTime) ? value : DateTime.parse(value))
      when :boolean   then (["true", "1"].include?(value.to_s))
      else value
    end
  rescue Exception => e
    raise StandardError, "Invalid value #{value.inspect} for attribute #{attribute_name} - expected data type is #{type.to_s.capitalize} but value is a #{value.class} (Exception details: #{e})"    
    value
  end
end

#inherited(klass) ⇒ Object

Initialises @attributes in the context of the class inheriting from the Tableless model



41
42
43
44
45
# File 'lib/tableless_model/class_methods.rb', line 41

def inherited(klass)
  super
  (@subclasses ||= Set.new) << klass
  klass.instance_variable_set("@attributes",  Hash.new)
end