Module: PlainQuery::InstanceMethods

Defined in:
lib/plain_query/instance_methods.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/plain_query/instance_methods.rb', line 5

def options
  @options
end

#relationObject (readonly)

Returns the value of attribute relation.



5
6
7
# File 'lib/plain_query/instance_methods.rb', line 5

def relation
  @relation
end

Instance Method Details

#exec_condition(condition) ⇒ Object

Executes if and unless conditions, conditions must contain object method name or proc (lambda)



43
44
45
46
47
48
49
50
51
# File 'lib/plain_query/instance_methods.rb', line 43

def exec_condition(condition)
  if [String, Symbol].member?(condition.class)
    !!send(condition)
  elsif condition.is_a?(Proc)
    !!instance_exec(&condition)
  else
    raise(StandardError, 'Condition must be method name or proc')
  end
end

#exec_queryObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/plain_query/instance_methods.rb', line 18

def exec_query
  @steps.each do |step_name, params|
    # Handles if condition
    if (params[:if] && !exec_condition(params[:if]))
      next
    end

    # Handles unless condition
    if (params[:unless] && exec_condition(params[:unless]))
      next
    end

    # Executes query mutation and checks that step returns ActiveRecord::Relation
    mutated_query = params[:query] ? params[:query].call(@relation, @options) : send(step_name)
    unless mutated_query.is_a?(ActiveRecord::Relation)
      raise(StandardError, 'Scope must be ActiveRecord::Relation')
    end

    @relation = mutated_query
  end

  @relation
end

#initialize(relation, options) ⇒ Object



7
8
9
10
11
12
13
14
15
16
# File 'lib/plain_query/instance_methods.rb', line 7

def initialize(relation, options)
  @relation = relation
  @options = options
  @steps = self.class.steps

  # Validates initial relation format. Allowed only ActiveRecord::Relation.
  unless @relation.is_a?(ActiveRecord::Relation)
    raise(StandardError, 'Queries accept only ActiveRecord::Relation as input')
  end
end