Class: Lore::Refined_Query

Inherits:
Object
  • Object
show all
Defined in:
lib/lore/query_shortcuts.rb

Direct Known Subclasses

Refined_Delete, Refined_Select, Refined_Update

Instance Method Summary collapse

Constructor Details

#initialize(accessor, statements = {}) ⇒ Refined_Query

Returns a new instance of Refined_Query.



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/lore/query_shortcuts.rb', line 6

def initialize(accessor, statements={})
  @accessor  = accessor
  @condition = statements[:condition]
  @what      = statements[:what]
  @limit     = statements[:limit]
  @offset    = statements[:offset]
  @order_by  = statements[:order_by]
  @order_by  = Array.new unless @order_by
  @group_by  = statements[:group_by]
  @having    = statements[:having]
  @condition = true unless @condition
#     @what = @what.to_s unless @what.nil?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, attribute_name) ⇒ Object

Provides wrapper for simple SQL attribute operation keywords. Examples:

Car.value_of.sum(Car.car_id).to_i   
-> SELECT sum(public.car.car_id) ...
-> Amount of all cars as integer, e.g. 2342
Car.value_of.max(Car.car_id).to_i   
-> SELECT max(public.car.car_id) ...
-> Highest car_id as integer, e.g. 14223


62
63
64
65
# File 'lib/lore/query_shortcuts.rb', line 62

def method_missing(method, attribute_name)
  @what = method.to_s << '(' << attribute_name.to_s << ') AS "value"'
  return self
end

Instance Method Details

#having(having_clause) ⇒ Object

Adds HAVING statement to query. Examples:

User.all.having(User.user_id.in( Admin.all(:user_id) ))


43
44
45
46
# File 'lib/lore/query_shortcuts.rb', line 43

def having(having_clause)
  @having = having_clause
  return self
end

#performObject

To be overloaded by derived classes



49
50
# File 'lib/lore/query_shortcuts.rb', line 49

def perform
end

#with(condition) ⇒ Object Also known as: where

Example: Adds where-condition to query. Multiple calls stack using AND. Examples;

Type.find(1).with(Type.name == 'foo' & Type.position > 2).having(<...>).ordered_by(:name).result 
# ... is same as ...
Type.find(1).with(Type.name == 'foo').with(Type.position > 2).having(<...>).ordered_by(:name).result 

User.all.with(User.user_id.in( Admin.all(:user_id) ))


29
30
31
32
33
34
35
36
# File 'lib/lore/query_shortcuts.rb', line 29

def with(condition)
  if((@condition.instance_of? TrueClass) || @condition.nil?) then 
    @condition = condition 
  else
    @condition = (@condition & condition)
  end
  return self
end