class MtgApi::QueryBuilder

builds queries to send to the api

Attributes

clazz[RW]

the stored class and query parameters

stored_conditions[RW]

the stored class and query parameters

stored_limit[RW]

the stored class and query parameters

stored_order[RW]

the stored class and query parameters

Public Class Methods

new(clazz) click to toggle source

store the class and initialize an empty conditions hash

# File lib/mtg_api/query_builder.rb, line 15
def initialize(clazz)
  self.clazz = clazz
  self.stored_conditions = {}
end

Public Instance Methods

all() click to toggle source

builds a request object and maps the responses onto the class

# 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) click to toggle source

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

# 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) click to toggle source

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

# 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) click to toggle source

store the conditions of this query if they are valid

# 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

Private Instance Methods

endpoint() click to toggle source

the configured endpoint, taking into account conditions

# File lib/mtg_api/query_builder.rb, line 64
def endpoint
  endpoint = clazz.config.endpoint.dup
  if stored_conditions.any?
    query_string = stored_conditions.map do |key, value|
      URI.escape("#{key}=#{value}")
    end
    endpoint << '?' + query_string.join('&')
  end
  endpoint
end