Module: SqlcachedClient::Arel

Included in:
Entity
Defined in:
lib/sqlcached_client/arel.rb

Instance Method Summary collapse

Instance Method Details

#build_arel(tables_map, arel_block) ⇒ Arel

Builds a SQL query executing the Arel statements in the given block.

Parameters:

  • tables_map (Hash)

    in the form of { :t1 => [:par1, :par2], :t2 => :par3, :t3 => nil }

  • arel_block (Proc)

Returns:

  • (Arel)

    an object that responds to ‘to_sql’



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
# File 'lib/sqlcached_client/arel.rb', line 14

def build_arel(tables_map, arel_block)
  table_names = tables_map.keys
  # attributes of this struct returns Arel tables named as the attribute
  context = Struct.new(*table_names).new(
    *table_names.map do |t_name|
      ArelWrapper.arel_module::Table.new(t_name)
    end
  )
  # build an Arel object evaluating the block if any
  arel_q =
    if arel_block
      context.instance_eval(&arel_block)
    else
      # no block given, add the default SELECT *
      context.send(tables_map.keys.first).project(
        ArelWrapper.arel_module.sql('*'))
    end
  # add the 'where' conditions passed as parameters (values in tables_map)
  tables_map.inject(arel_q) do |query_acc, item|
    t_name, parameters = item
    table = context.send(t_name)
    parameters ||= []
    parameters = [parameters] if !parameters.respond_to?(:inject)
    parameters.inject(query_acc) do |arel, param|
      arel.where(table[param].eq("{{ #{param} }}"))
    end
  end
end