Created
June 9, 2016 13:45
-
-
Save technicalpickles/ea4787a1be5934760b0a4ce3f72abbb1 to your computer and use it in GitHub Desktop.
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
require 'faraday' | |
require 'faraday_middleware' | |
module Icecast | |
class Admin < Faraday::Connection | |
class Error < RuntimeError | |
end | |
class AdminError < Error | |
end | |
class AuthenticationError < Error | |
end | |
class ConnectionError < Error | |
end | |
class RaiseAuthenticationErrorOn401 < Faraday::Middleware | |
def call(env) | |
response = @app.call env | |
if response.status == 401 | |
raise AuthenticationError, response.body | |
else | |
response | |
end | |
end | |
end | |
class ParseNumbersAndTimestamps < Faraday::Response::Middleware | |
def parse(body) | |
case body | |
when Hash, ::Hashie::Mash | |
body.each do |key, value| | |
if key =~ /iso8601\z/ | |
body[key] = Time.parse(value) | |
else | |
case value | |
when Hash | |
body[key] = parse(value) | |
when /\A\d+\z/ | |
body[key] = value.to_i | |
end | |
end | |
end | |
body | |
else | |
raise "Can't parse times of #{body.class}: #{body}" | |
end | |
end | |
end | |
class RaiseAdminErrorOnNon200 < Faraday::Middleware | |
def call(env) | |
response = @app.call env | |
unless [200, 201, 204].include?(response.status) | |
url = response.env[:url].to_s | |
message = "Got HTTP #{response['status']} back for #{url}\n" | |
message += response.body | |
raise AdminError, response.body | |
else | |
response | |
end | |
end | |
end | |
class CustomizeFaradayErrors < Faraday::Middleware | |
def call(env) | |
begin | |
@app.call(env) | |
rescue Faraday::Error::ConnectionFailed | |
raise ConnectionError | |
end | |
end | |
end | |
def initialize(base_url) | |
super :url => "#{base_url}/admin" do |conn| | |
conn.use ParseNumbersAndTimestamps | |
conn.response :xml | |
conn.use RaiseAdminErrorOnNon200 | |
conn.use RaiseAuthenticationErrorOn401 | |
conn.use CustomizeFaradayErrors | |
conn.adapter Faraday.default_adapter | |
end | |
end | |
def numericize_values(hash) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment