Class: RecordCache::Query

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

Overview

Container for the Query parameters

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(equality = nil) ⇒ Query

Returns a new instance of Query.



7
8
9
10
11
12
# File 'lib/record_cache/query.rb', line 7

def initialize(equality = nil)
  @wheres = equality || {}
  @sort_orders = []
  @limit = nil
  @where_ids = {}
end

Instance Attribute Details

#limitObject

Returns the value of attribute limit.



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

def limit
  @limit
end

#sort_ordersObject (readonly)

Returns the value of attribute sort_orders.



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

def sort_orders
  @sort_orders
end

#wheresObject (readonly)

Returns the value of attribute wheres.



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

def wheres
  @wheres
end

Instance Method Details

#cache_keyObject

retrieve a unique key for this Query (used in RequestCache)



48
49
50
# File 'lib/record_cache/query.rb', line 48

def cache_key
  @cache_key ||= generate_key
end

#order_by(attribute, ascending = true) ⇒ Object

Add a sort order to the query



35
36
37
# File 'lib/record_cache/query.rb', line 35

def order_by(attribute, ascending = true)
  @sort_orders << [attribute.to_s, ascending]
end

#sorted?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/record_cache/query.rb', line 39

def sorted?
  @sort_orders.size > 0
end

#to_sObject



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

def to_s
  s = "SELECT "
  s << @wheres.map{|k,v| "#{k} = #{v.inspect}"}.join(" AND ")
  if @sort_orders.size > 0
    order_by = @sort_orders.map{|attr,asc| "#{attr} #{asc ? 'ASC' : 'DESC'}"}.join(', ')
    s << " ORDER_BY #{order_by}"
  end
  s << " LIMIT #{@limit}" if @limit
  s
end

#where(attribute, values) ⇒ Object

Set equality of an attribute (usually found in where clause)



15
16
17
# File 'lib/record_cache/query.rb', line 15

def where(attribute, values)
  @wheres[attribute.to_sym] = values if attribute
end

#where_id(attribute) ⇒ Object

Retrieve the single id (positive integer) for the given attribute from the where statements Returns nil if no the attribute is not present, or if it contains an array



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

def where_id(attribute)
  ids = where_ids(attribute)
  return nil unless ids && ids.size == 1
  ids.first
end

#where_ids(attribute) ⇒ Object

Retrieve the ids (array of positive integers) for the given attribute from the where statements Returns nil if no the attribute is not present



21
22
23
24
# File 'lib/record_cache/query.rb', line 21

def where_ids(attribute)
  return @where_ids[attribute] if @where_ids.key?(attribute)
  @where_ids[attribute] ||= array_of_positive_integers(@wheres[attribute])
end