Class: Ambition::Query
- Inherits:
-
Object
show all
- Defined in:
- lib/ambition/lib/ambition/query.rb
Constant Summary
collapse
- @@select =
'SELECT * FROM %s %s'
Instance Method Summary
collapse
Constructor Details
#initialize(owner) ⇒ Query
Returns a new instance of Query.
5
6
7
8
9
|
# File 'lib/ambition/lib/ambition/query.rb', line 5
def initialize(owner)
@table_name = owner.table_name
@owner = owner
@clauses = []
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
20
21
22
23
24
|
# File 'lib/ambition/lib/ambition/query.rb', line 20
def method_missing(method, *args, &block)
with_context do
@owner.send(method, *args, &block)
end
end
|
Instance Method Details
#add(clause) ⇒ Object
11
12
13
14
|
# File 'lib/ambition/lib/ambition/query.rb', line 11
def add(clause)
@clauses << clause
self
end
|
#keyed_clauses ⇒ Object
71
72
73
74
75
76
77
78
79
80
81
82
83
|
# File 'lib/ambition/lib/ambition/query.rb', line 71
def keyed_clauses
@clauses.inject({}) do |hash, clause|
hash[clause.key] ||= []
hash[clause.key] << clause.to_s
if clause.respond_to?(:includes) && !clause.includes.blank?
hash[:includes] ||= []
hash[:includes] << clause.includes
end
hash
end
end
|
#query_context ⇒ Object
16
17
18
|
# File 'lib/ambition/lib/ambition/query.rb', line 16
def query_context
self
end
|
#to_hash ⇒ Object
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
# File 'lib/ambition/lib/ambition/query.rb', line 34
def to_hash
keyed = keyed_clauses
hash = {}
unless (where = keyed[:conditions]).blank?
hash[:conditions] = Array(where)
hash[:conditions] *= ' AND '
end
unless (includes = keyed[:includes]).blank?
hash[:includes] = includes.flatten
end
if order = keyed[:order]
hash[:order] = order.join(', ')
end
if limit = keyed[:limit]
hash[:limit] = limit.join(', ')
end
hash
end
|
#to_s ⇒ Object
Also known as:
to_sql
58
59
60
61
62
63
64
65
66
67
68
|
# File 'lib/ambition/lib/ambition/query.rb', line 58
def to_s
hash = keyed_clauses
sql = []
sql << "JOIN #{hash[:includes].join(', ')}" unless hash[:includes].blank?
sql << "WHERE #{hash[:conditions].join(' AND ')}" unless hash[:conditions].blank?
sql << "ORDER BY #{hash[:order].join(', ')}" unless hash[:order].blank?
sql << "LIMIT #{hash[:limit].join(', ')}" unless hash[:limit].blank?
@@select % [ @table_name, sql.join(' ') ]
end
|
#with_context ⇒ Object
26
27
28
29
30
31
32
|
# File 'lib/ambition/lib/ambition/query.rb', line 26
def with_context
@owner.query_context = self
ret = yield
ensure
@owner.query_context = nil
ret
end
|