Class: DeltaForce::ChangeProxy

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ ChangeProxy

Returns a new instance of ChangeProxy.



7
8
9
# File 'lib/delta_force/change_proxy.rb', line 7

def initialize(klass)
  @klass = klass
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



5
6
7
# File 'lib/delta_force/change_proxy.rb', line 5

def klass
  @klass
end

Instance Method Details

#values(*value_fields) ⇒ Object Also known as: value



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
# File 'lib/delta_force/change_proxy.rb', line 11

def values(*value_fields)
  options = value_fields.extract_options!.symbolize_keys

  partition_key = options[:by].to_s
  partition_column = "#{table_name}.#{partition_key}"
  id_column = "#{table_name}.id"

  period_field_name = options[:over].to_s
  period_column = "#{table_name}.#{period_field_name}"

  scope_name = options[:scope_name] || default_scope_name(value_fields, options)

  window = "
    (
       PARTITION BY #{partition_column}
       ORDER BY #{period_column} DESC, #{id_column} DESC ROWS
       BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
    )"

  value_expressions = value_fields.collect do |value_field|
    value_field_name = value_field.to_s
    value_column = "#{table_name}.#{value_field_name}"

    [
      "last_value(#{value_column}) over #{window} as opening_#{value_field_name}",
      "first_value(#{value_column}) over #{window} as closing_#{value_field_name}"
    ]
  end.flatten

  klass.named_scope scope_name, :select => "distinct #{partition_column},
    last_value(#{period_column}) over #{window} as opening_#{period_field_name},
    first_value(#{period_column}) over #{window} as closing_#{period_field_name},
    #{value_expressions.join ','}
  "

  value_fields.each do |value_field|
    klass.class.send :define_method, "#{value_field}_by_#{options[:by].to_s}_as_of_#{options[:over].to_s}" do |period|
      Hash[
        scoped(
          :select => "distinct #{partition_column},
            first_value(#{table_name}.#{value_field.to_s}) over #{window} as #{value_field.to_s}",
          :conditions => [ "#{period_column} <= ?", period]
        ).index_by(&partition_key.to_sym).map{|k,v| [k, v[value_field]]}
      ]
    end
  end
end