Created
December 14, 2011 13:35
-
-
Save sj26/1476586 to your computer and use it in GitHub Desktop.
HTTParty extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExampleClient | |
include HTTParty | |
extend HTTPExceptions | |
parser Class.new HTTParty::Parser | |
parser.send :include, PresentParser | |
parser.send :include, MashedParser | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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