Skip to content

Instantly share code, notes, and snippets.

@sj26
Created December 14, 2011 13:35
Show Gist options
  • Save sj26/1476586 to your computer and use it in GitHub Desktop.
Save sj26/1476586 to your computer and use it in GitHub Desktop.
HTTParty extensions
class ExampleClient
include HTTParty
extend HTTPExceptions
parser Class.new HTTParty::Parser
parser.send :include, PresentParser
parser.send :include, MashedParser
end
# Raise an exception for responses with 4xx and 5xx status codes.
# Use PresentParser so parsing an error response doesn't raise.
module HTTPExceptions
def perform_request http_method, path, options
response = super
response.error! if response.response.is_a?(Net::HTTPClientError) or response.response.is_a?(Net::HTTPServerError)
response
end
end
# Turns XML, JSON and YAML bodies into `Hashie::Mash`s.
module MashedParser
protected
def xml
mashed super
end
def json
mashed super
end
def yaml
mashed super
end
private
def mashed thing
if thing.is_a? Hash
Hashie::Mash.new thing
elsif thing.is_a? Array
thing.map &method(:mashed)
else
thing
end
end
end
# Only parses body if present.
module PresentParser
protected
def xml
super unless body.blank?
end
def json
super unless body.blank?
end
def yaml
super unless body.blank?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment