Class: EasyMapper::Query

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model) ⇒ Query

Returns a new instance of Query.



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

def initialize(model)
  @model = model
  @where = {}
  @order = {}
end

Instance Attribute Details

#modelObject

Returns the value of attribute model.



5
6
7
# File 'lib/easy_mapper/query.rb', line 5

def model
  @model
end

Instance Method Details

#allObject



65
66
67
# File 'lib/easy_mapper/query.rb', line 65

def all
  where({}).exec
end

#avg(field) ⇒ Object



82
83
84
# File 'lib/easy_mapper/query.rb', line 82

def avg(field)
  @model.repository.aggregate('AVG', field, @where).to_f
end

#count(field = '*') ⇒ Object



78
79
80
# File 'lib/easy_mapper/query.rb', line 78

def count(field = '*')
  @model.repository.aggregate('COUNT', field, @where)
end

#delete_allObject



94
95
96
# File 'lib/easy_mapper/query.rb', line 94

def delete_all
  @model.repository.delete({})
end

#each(&block) ⇒ Object



74
75
76
# File 'lib/easy_mapper/query.rb', line 74

def each(&block)
  exec.each(&block)
end

#execObject



61
62
63
# File 'lib/easy_mapper/query.rb', line 61

def exec
  map_to_model_instances @model.repository.find(self)
end

#inspectObject



90
91
92
# File 'lib/easy_mapper/query.rb', line 90

def inspect
  exec.inspect
end

#limit(value = nil) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/easy_mapper/query.rb', line 41

def limit(value = nil)
  return @limit unless value

  @limit = value

  self
end

#offset(value = nil) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/easy_mapper/query.rb', line 49

def offset(value = nil)
  return @offset unless value

  @offset = value

  self
end

#order(fields = nil) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/easy_mapper/query.rb', line 29

def order(fields = nil)
  return @order unless fields

  if @order
    @order.merge!(fields)
  else
    @order = fields
  end

  self
end

#single_resultObject



69
70
71
72
# File 'lib/easy_mapper/query.rb', line 69

def single_result
  # TODO: return single result, raise exception if none or more
  exec.first
end

#sum(field) ⇒ Object



86
87
88
# File 'lib/easy_mapper/query.rb', line 86

def sum(field)
  @model.repository.aggregate('SUM', field, @where)
end

#where(query = nil) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/easy_mapper/query.rb', line 17

def where(query = nil)
  return @where unless query

  if @where
    @where.merge!(query)
  else
    @where = query
  end

  self
end