Class: ActiveRecord::Relation

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

Instance Method Summary collapse

Instance Method Details

#calculated(*args) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/calculated_attributes/model_methods.rb', line 68

def calculated(*args)
  projections = arel.projections
  args.each do |arg|
    lam = klass.calculated.calculated[arg] || klass.base_class.calculated.calculated[arg]
    sql = lam.call
    new_projection = 
      if sql.is_a?(String)
        Arel.sql("(#{sql})").as(arg.to_s)
      elsif sql.respond_to? :to_sql
        Arel.sql("(#{sql.to_sql})").as(arg.to_s)
      else
        sql.as(arg.to_s)
      end
    new_projection.calculated_attr!
    projections.push new_projection
  end
  select(projections)
end