Class: Query

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

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ Query

Returns a new instance of Query.



3
4
5
# File 'lib/query.rb', line 3

def initialize(klass)
  @klass = klass
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/query.rb', line 55

def method_missing(meth, *args, &block)
  if Array.method_defined?(meth)
    all.send(meth, *args, &block)
  else
    super
  end
end

Instance Method Details

#allObject



51
52
53
# File 'lib/query.rb', line 51

def all
  execute
end

#count(count = 1) ⇒ Object

TODO: make this work def skip(skip)

criteria[:skip] = skip
self

end



27
28
29
30
31
# File 'lib/query.rb', line 27

def count(count=1)
  criteria[:count] = count
  #self
  all
end

#criteriaObject



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

def criteria
  @criteria ||= { :conditions => {} }
end

#executeObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/query.rb', line 33

def execute
  params = {}
  params.merge!({:where => criteria[:conditions].to_json}) if criteria[:conditions]
  params.merge!({:limit => criteria[:limit].to_json}) if criteria[:limit]
  params.merge!({:skip => criteria[:skip].to_json}) if criteria[:skip]
  params.merge!({:count => criteria[:count].to_json}) if criteria[:count]

  resp = @klass.resource.get(:params => params)

  if criteria[:count] == 1
    results = JSON.parse(resp)['count']
    return results.to_i
  else
    results = JSON.parse(resp)['results']
    return results.map {|r| @klass.model_name.constantize.new(r, false)}
  end
end

#limit(limit) ⇒ Object



16
17
18
19
# File 'lib/query.rb', line 16

def limit(limit)
  criteria[:limit] = limit
  self
end

#respond_to?(meth) ⇒ Boolean

Returns:

  • (Boolean)


63
64
65
66
67
68
69
# File 'lib/query.rb', line 63

def respond_to?(meth)
  if Array.method_defined?(meth)
    true
  else
    super
  end
end

#where(args) ⇒ Object



11
12
13
14
# File 'lib/query.rb', line 11

def where(args)
  criteria[:conditions].merge!(args)
  self
end