Class: MtgApi::QueryBuilder

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/mtg_api/query_builder.rb

Overview

builds queries to send to the api

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(clazz) ⇒ QueryBuilder

store the class and initialize an empty conditions hash



15
16
17
18
# File 'lib/mtg_api/query_builder.rb', line 15

def initialize(clazz)
  self.clazz = clazz
  self.stored_conditions = {}
end

Instance Attribute Details

#clazzObject

the stored class and query parameters



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

def clazz
  @clazz
end

#stored_conditionsObject

the stored class and query parameters



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

def stored_conditions
  @stored_conditions
end

#stored_limitObject

the stored class and query parameters



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

def stored_limit
  @stored_limit
end

#stored_orderObject

the stored class and query parameters



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

def stored_order
  @stored_order
end

Instance Method Details

#allObject

builds a request object and maps the responses onto the class



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/mtg_api/query_builder.rb', line 21

def all
  response = Request.new(endpoint).response_for(clazz.config.response_key)
  response = response[0...stored_limit] unless stored_limit.nil?

  response.map! do |attributes|
    clazz.new(attributes)
  end
  response.sort_by!(&stored_order.to_proc) unless stored_order.nil?

  response
end

#limit(limit) ⇒ Object

store the limit to the response of the query if it is valid



34
35
36
37
38
39
# File 'lib/mtg_api/query_builder.rb', line 34

def limit(limit)
  fail ArgumentError, "Invalid limit given: #{limit}" unless limit > 0

  self.stored_limit = limit
  self
end

#order(order) ⇒ Object

store the order to sort the response of the query if it is valid



42
43
44
45
46
47
48
49
# File 'lib/mtg_api/query_builder.rb', line 42

def order(order)
  unless clazz.attributes.include?(order)
    fail ArgumentError, "Invalid order given: #{order}"
  end

  self.stored_order = order
  self
end

#where(conditions) ⇒ Object

store the conditions of this query if they are valid



52
53
54
55
56
57
58
59
# File 'lib/mtg_api/query_builder.rb', line 52

def where(conditions)
  if (invalid = (conditions.keys - clazz.attributes)).any?
    fail ArgumentError, "Invalid conditions given: #{invalid.join(', ')}"
  end

  stored_conditions.merge!(conditions)
  self
end