Class: Squirm::Model::MethodDefiner

Inherits:
Object
  • Object
show all
Defined in:
lib/squirm/model/method_definer.rb

Instance Method Summary collapse

Constructor Details

#initialize(model_class) ⇒ MethodDefiner

Returns a new instance of MethodDefiner.



6
7
8
# File 'lib/squirm/model/method_definer.rb', line 6

def initialize(model_class)
  @model_class = model_class
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/squirm/model/method_definer.rb', line 31

def method_missing(sym, *args)
  attribute = sym.to_s.tr("=", "")
  value     = args.first
  base      = '@__attributes["%s"]'
  cast = begin
    case value
    when Float      then base + '.to_f'
    when Rational   then base + '.to_r'
    when Complex    then base + '.to_c'
    when Symbol     then base + '.to_sym'
    when Numeric    then base + '.to_i'
    when TrueClass  then base + ' == "t"'
    when FalseClass then base + ' == "t"'
    when DateTime   then "DateTime.parse(#{base})"
    when Date       then "Date.parse(#{base})"
    else base + ".to_s"
    end
  end
  define_getter(attribute, cast)
  define_setter(attribute) unless value.frozen?
end

Instance Method Details

#define_getter(attribute, code) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/squirm/model/method_definer.rb', line 10

def define_getter(attribute, code)
  @model_class.class_eval(<<-EOD, __FILE__, __LINE__ + 1)
    def #{attribute}
      if defined? @#{attribute}
        @#{attribute}
      else
        return unless @__attributes.key?("#{attribute}")
        #{code % attribute}
      end
    end
  EOD
end

#define_setter(attribute) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/squirm/model/method_definer.rb', line 23

def define_setter(attribute)
  @model_class.class_eval(<<-EOD, __FILE__, __LINE__ + 1)
    def #{attribute}=(value)
      @#{attribute} = value
    end
  EOD
end