Class: Ambition::Adapters::ActiveRecord::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/ambition/adapters/active_record/query.rb

Constant Summary collapse

@@select =
'SELECT * FROM %s %s'

Instance Method Summary collapse

Instance Method Details

#kickObject



7
8
9
# File 'lib/ambition/adapters/active_record/query.rb', line 7

def kick
  owner.find(:all, to_hash)
end

#sizeObject Also known as: length



11
12
13
# File 'lib/ambition/adapters/active_record/query.rb', line 11

def size
  owner.count(to_hash)
end

#to_hashObject



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
# File 'lib/ambition/adapters/active_record/query.rb', line 16

def to_hash
  hash = {}

  unless (joins = stash[:joins]).blank?
    hash[:joins] = joins
    stash[:include] -= stash[:joins] unless stash[:include].blank?
  end

  unless (where = clauses[:select]).blank?
    hash[:conditions] = Array(where)
    hash[:conditions] *= ' AND '
  end

  unless (order = clauses[:sort]).blank?
    hash[:order] = order.join(', ')
  end

  if Array(clauses[:slice]).last =~ /LIMIT (\d+)/
    hash[:limit] = $1.to_i
  end

  if Array(clauses[:slice]).last =~ /OFFSET (\d+)/
    hash[:offset] = $1.to_i
  end

  hash[:include] = stash[:include] if stash[:include]

  hash
end

#to_sObject Also known as: to_sql



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ambition/adapters/active_record/query.rb', line 46

def to_s
  hash = to_hash

  raise "Sorry, I can't construct SQL with complex joins (yet)" unless hash[:include].blank?

  sql = []
  sql << joins_sql(hash[:joins])      unless hash[:joins].blank?
  sql << "WHERE #{hash[:conditions]}" unless hash[:conditions].blank?
  sql << "ORDER BY #{hash[:order]}"   unless hash[:order].blank?
  sql << clauses[:slice].last         unless hash[:slice].blank?

  @@select % [ owner.table_name, sql.join(' ') ]
end