Module: Cockpit::AR::Support

Defined in:
lib/cockpit/stores/active_record.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/cockpit/stores/active_record.rb', line 10

def self.included(base)
  base.class_eval do
    has_many :settings, :as => :configurable, :class_name => "::Cockpit::AR::Setting", :dependent => :destroy
    
    class << self
      def setting_sum(key, conditions = {})
        conditions[:configurable_type] ||= self.sti_classes
        conditions[:key] = key
        if defined?(::ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) && connection.is_a?(::ActiveRecord::ConnectionAdapters::PostgreSQLAdapter)
          select = "INTEGER"
        else
          select = "SIGNED"
        end
        select = "CAST(#{::Cockpit::AR::Setting.quoted_table_name}.value AS #{select})"
        Setting.sum(:value, :conditions => conditions, :select => select)
      end
      alias setting_total setting_sum
      
      def setting_average(key, conditions = {})
        conditions[:configurable_type] ||= self.sti_classes
        conditions[:key] = key
        if defined?(::ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) && connection.is_a?(::ActiveRecord::ConnectionAdapters::PostgreSQLAdapter)
          select = "INTEGER"
        else
          select = "SIGNED"
        end
        select = "CAST(#{::Cockpit::AR::Setting.quoted_table_name}.value AS #{select})"
        Setting.average(:value, :conditions => conditions, :select => select)
      end
      alias setting_avg setting_average
      
      def method_missing(method, *args, &block)
        if method.to_s =~ /(total|sum|average|avg)_(\w+)/
          self.send("setting_#{$1}", $2, args.extract_options!)
        else
          super(method, *args, &block)
        end
      end
    end
    
    unless respond_to?("get")
      def get(key)
        cockpit[key]
      end
    end
    
    unless respond_to?("set")
      def set(key, value)
        cockpit[key] = value
      end
    end
  end
end