Class: ActiveRecord::Base

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

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/calculated_attributes/model_methods.rb', line 30

def method_missing(sym, *args)
  no_sym_in_attr =
    if @attributes.respond_to? :include?
      !@attributes.include?(sym.to_s)
    else
      !@attributes.key?(sym.to_s)
    end
  if no_sym_in_attr && (self.class.calculated.calculated[sym] || self.class.base_class.calculated.calculated[sym])
    Rails.logger.warn("Using calculated value without including it in the relation: #{sym}") if defined? Rails
    class_with_attr =
      if self.class.calculated.calculated[sym]
        self.class
      else
        self.class.base_class
      end
    if class_with_attr.respond_to? :scoped
      class_with_attr.scoped.calculated(sym => args).find(id).send(sym)
    else
      class_with_attr.all.calculated(sym => args).find(id).send(sym)
    end
  else
    super
  end
end

Instance Method Details

#calculated(*args) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/calculated_attributes/model_methods.rb', line 22

def calculated(*args)
  if self.class.respond_to? :scoped
    self.class.scoped.calculated(*args).find(id)
  else
    self.class.all.calculated(*args).find(id)
  end
end

#respond_to_missing?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
59
60
61
62
63
64
65
# File 'lib/calculated_attributes/model_methods.rb', line 55

def respond_to_missing?(method, include_private = false)
  no_sym_in_attr =
    if @attributes.respond_to? :include?
      !@attributes.include?(method.to_s)
    elsif @attributes.respond_to? :key?
      !@attributes.key?(method.to_s)
    else
      true
    end
  super || (no_sym_in_attr && (self.class.calculated.calculated[method] || self.class.base_class.calculated.calculated[method]))
end