Module: Arlj::Base

Included in:
Arlj
Defined in:
lib/arlj/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.memoize!Object



3
4
5
6
7
# File 'lib/arlj/base.rb', line 3

def self.memoize!
  require 'memoist'
  self.extend Memoist
  self.memoize :arlj_sql, :arlj_aggregate_sql
end

Instance Method Details

#arlj(assoc) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/arlj/base.rb', line 9

def arlj(assoc)
  # Example snippet:
  #  LEFT JOIN [assoc]
  #         ON [assoc].source_id = source.id

  joins(arlj_sql(assoc))
end

#arlj_aggregate(assoc, *args) ⇒ Object

Example usage:

arlj_aggregate(other, 'count(*)', 'sum(col)' => target_name)


19
20
21
22
23
24
25
26
27
# File 'lib/arlj/base.rb', line 19

def arlj_aggregate(assoc, *args)
  # Example snippet:
  #  LEFT JOIN(SELECT source_id, [func]([column]) AS [target_name]
  #              FROM [assoc]
  #             GROUP BY [assoc].source_id) arlj_aggregate_[assoc]
  #         ON [assoc].source_id = source.id

  joins(arlj_aggregate_sql(assoc, *args))
end

#arlj_aggregate_arel(assoc, *args) ⇒ Object



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
63
64
65
66
# File 'lib/arlj/base.rb', line 38

def arlj_aggregate_arel(assoc, *args)
  options = args.extract_options!

  refl = reflect_on_association(assoc)
  refl_arel = refl.klass.arel_table

  subq_ar = refl.klass.group(refl_arel[refl.foreign_key])

  columns = [refl_arel[refl.foreign_key]]
  args.each do |arg|
    columns << parse_directive(refl, assoc, refl_arel, arg)
  end
  options.each do |key, value|
    if directive?(key)
      columns << parse_directive(refl, assoc, refl_arel, key, value)
    elsif key.to_s == 'where'
      subq_ar = subq_ar.send(key, value)
    else
      raise "'#{key.inspect} => #{value.inspect}' not recognized"
    end
  end

  subq_arel = subq_ar.arel
  subq_arel.projections.clear
  subq_arel = subq_arel.project(columns).
                as("arlj_aggregate_#{refl.table_name}")

  arlj_left_join_arel(subq_arel, refl.foreign_key)
end

#arlj_aggregate_sql(assoc, *args) ⇒ Object



68
69
70
# File 'lib/arlj/base.rb', line 68

def arlj_aggregate_sql(assoc, *args)
  arlj_aggregate_arel(assoc, *args).join_sources
end

#arlj_arel(assoc) ⇒ Object



29
30
31
32
# File 'lib/arlj/base.rb', line 29

def arlj_arel(assoc)
  refl = reflect_on_association(assoc)
  arlj_left_join_arel(refl.klass.arel_table, refl.foreign_key)
end

#arlj_sql(assoc) ⇒ Object



34
35
36
# File 'lib/arlj/base.rb', line 34

def arlj_sql(assoc)
  arlj_arel(assoc).join_sources
end