Class: Module

Inherits:
Object
  • Object
show all
Defined in:
lib/virtual_attribute/virtual_attribute.rb

Instance Method Summary collapse

Instance Method Details

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



2
3
4
5
6
7
8
9
10
11
12
13
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
47
48
49
50
# File 'lib/virtual_attribute/virtual_attribute.rb', line 2

def virtual_attribute( name, options={} )
  name_equals = "#{name.to_s}="
  inst_var = "@#{name.to_s}"
  module_eval do 

    if options[:boolean] or (options[:type] == :boolean)
      define_method(name_equals) do |val|
        val = val.to_s.strip
        if ['1', 'true', 'yes'].include?(val)
          instance_variable_set(inst_var, true)
        elsif ['0', 'false', 'no'].include?(val)
          instance_variable_set(inst_var, false)
        end
      end
    elsif (options[:type] == :float)
      define_method(name_equals) do |val|
        begin
          instance_variable_set(inst_var, Float(val))
        rescue ArgumentError
          instance_variable_set(inst_var, nil)
        end
      end
    elsif (options[:type] == :integer)
      define_method(name_equals) do |val|
        begin
          instance_variable_set(inst_var, Integer(val))
        rescue ArgumentError
          instance_variable_set(inst_var, nil)
        end
      end
    else
      define_method(name_equals) do |val|
        instance_variable_set(inst_var, val)
      end
    end

    if [:date, :time, :datetime].include? options[:type]
      columns_hash[name.to_s] = ActiveRecord::ConnectionAdapters::Column.new(name.to_s, nil, options[:type].to_s)
    end

    define_method(name) do
      instance_variable_get(inst_var)
    end

    if options[:attr_type] && self.respond_to?(options[:attr_type])
      self.send(options[:attr_type], name)
    end
  end
end