Module: Sakuramochi::Relation

Extended by:
ActiveSupport::Concern
Defined in:
lib/sakuramochi/relation.rb

Instance Method Summary collapse

Instance Method Details

#build_where_with_condition(opts, other = []) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/sakuramochi/relation.rb', line 47

def build_where_with_condition(opts, other = [])
  if Sakuramochi::Condition.condition?(opts)
    ast = Sakuramochi::Condition::Parser.new(opts.dup).parse
    [collapse_conditions(ast, other)].compact
  else
    build_where_without_condition(opts, other)
  end
end

#collapse_conditions(node, other) ⇒ Object



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
# File 'lib/sakuramochi/relation.rb', line 13

def collapse_conditions(node, other)
  case node
  when Sakuramochi::Condition::Nodes::Expression
    case node.operator.to_s
    when 'and'
      left = collapse_conditions(node.left, other)
      right = collapse_conditions(node.right, other)
      left && right ? Arel::Nodes::And.new([left, right]) : left || right

    when 'or'
      left = collapse_conditions(node.left, other)
      right = collapse_conditions(node.right, other)
      left && right ? Arel::Nodes::Or.new(left, right) : left || right
    end

  when Sakuramochi::Condition::Nodes::Term
    case node.operator.to_s
    when 'not'
      right = collapse_conditions(node.value, other)
      Arel::Nodes::Not.new(right) if right
    end

  when Sakuramochi::Condition::Nodes::Factor
    wheres = build_where_without_condition(node.value, other)
    arel = table.from(table)
    collapse_wheres(arel, (wheres - ['']).uniq)
    arel.constraints.inject { |left, right| left.and(right) }

  when Sakuramochi::Condition::Nodes::Group
    expression = collapse_conditions(node.expression, other)
    Arel::Nodes::Grouping.new(expression) if expression
  end
end