lib/relax/request.rb in relax-0.0.1 vs lib/relax/request.rb in relax-0.0.2
- old
+ new
@@ -1,8 +1,10 @@
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
@@ -10,39 +12,50 @@
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
- keys.sort { |a, b| a.to_s <=> b.to_s }.collect do |key|
- "#{key.to_s}=#{ERB::Util.url_encode(send('[]', key).to_s)}"
- end.join('&')
+ to_query.to_s
end
class << self
+ # Specifies a parameter to create on the request class.
+ #
+ # Options:
+ # - <tt>:value</tt>: 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