require 'relax/query' module Relax # Request is intended to be a parent class for requests passed to # Service#call. class Request def initialize(options = {}) self.class.class_variables.each do |variable| instance_variable_set(variable.slice(1..-1), self.class.send(:class_variable_get, variable)) end options.each do |key, value| instance_variable_set "@#{key}", value end end # Converts this request into a Query object. def to_query keys.inject(Query.new) do |parameters, key| parameters[convert_key(key)] = send(key) parameters end end # Converts this request into a query string for use in a URL. def to_s to_query.to_s end class << self # Specifies a parameter to create on the request class. # # Options: # - :value: The default value for this parameter. def parameter(name, options = {}) attr_accessor name class_variable_set("@@#{name}", options.delete(:value)) if options[:value] end # Adds a template value to a request class. Equivalent to creating a # parameter with a default value. def []=(key, value) parameter(key, {:value => value}) end end protected # Returns an array of the parameter names for this request. def keys instance_variables.collect { |v| v.sub('@', '') } end # Converts a key when the Request is converted to a query. By default, no # conversion actually takes place, but this method can be overridden by # child classes to perform standard manipulations, such as replacing # underscores. def convert_key(key) key end end end