0
@@ -12,13 +12,13 @@ dir = File.expand_path(File.join(File.dirname(__FILE__), 'httparty'))
0
require dir + '/core_ext'
0
+ class UnsupportedFormat < StandardError; end
0
def self.included(base)
0
base.extend ClassMethods
0
- class UnsupportedFormat < StandardError; end
0
- AllowedFormats = %w[xml json]
0
+ AllowedFormats = {:xml => 'text/xml', :json => 'application/json'}
0
@@ -64,8 +64,7 @@ module HTTParty
0
- raise UnsupportedFormat, "Must be one of: #{AllowedFormats.join(', ')}" unless AllowedFormats.include?(f)
0
+ raise UnsupportedFormat, "Must be one of: #{AllowedFormats.keys.join(', ')}" unless AllowedFormats.key?(f)
0
@@ -111,9 +110,6 @@ module HTTParty
0
raise ArgumentError, 'only get, post, put and delete methods are supported' unless %w[get post put delete].include?(method.to_s)
0
raise ArgumentError, ':headers must be a hash' if options[:headers] && !options[:headers].is_a?(Hash)
0
raise ArgumentError, ':basic_auth must be a hash' if options[:basic_auth] && !options[:basic_auth].is_a?(Hash)
0
- # we always want path that begins with /
0
- path = path =~ /^(\/|https?:\/\/)/ ? path : "/#{path}"
0
- @format ||= format_from_path(path)
0
uri = URI.parse("#{base_uri}#{path}")
0
existing_query = uri.query ? "#{uri.query}&" : ''
0
uri.query = if options[:query].blank?
0
@@ -129,9 +125,10 @@ module HTTParty
0
# note to self: self, do not put basic auth above headers because it removes basic auth
0
request.basic_auth(basic_auth[:username], basic_auth[:password]) if basic_auth
0
response = http(uri).request(request)
0
+ @format ||= format_from_mimetype(response['content-type'])
0
- when Net::HTTPSuccess
then0
parse_response(response.body)
0
response.instance_eval { class << self; attr_accessor :body_parsed; end }
0
@@ -143,9 +140,9 @@ module HTTParty
0
def parse_response(body) #:nodoc:
0
ActiveSupport::JSON.decode(body)
0
# just return the response if no format
0
@@ -158,13 +155,10 @@ module HTTParty
0
str =~ /^https?:\/\// ? str : "http#{'s' if str.include?(':443')}://#{str}"
0
- # Returns a format that we can handle from the path if possible.
0
- # Just does simple pattern matching on file extention:
0
- # /foobar.xml => 'xml'
0
- # /foobar.json => 'json'
0
- def format_from_path(path) #:nodoc:
0
- ext = File.extname(path)[1..-1]
0
- !ext.blank? && AllowedFormats.include?(ext) ? ext : nil
0
+ # Uses the HTTP Content-Type header to determine the format of the response
0
+ # It compares the MIME type returned to the types stored in the AllowedFormats hash
0
+ def format_from_mimetype(mimetype) #:nodoc:
0
+ AllowedFormats.each { |k, v| return k if mimetype.include?(v) }
0
\ No newline at end of file