Skip to content

Instantly share code, notes, and snippets.

@myronmarston
Created June 20, 2012 04:06
Show Gist options
  • Save myronmarston/2958081 to your computer and use it in GitHub Desktop.
Save myronmarston/2958081 to your computer and use it in GitHub Desktop.
Example of allowing a faraday connection to be configured through middleware blocks.
module Silo
module Client
extend self
def configuration
@configuration ||= Configuration.new
end
def configure
yield configuration
end
def connection
@connection ||= begin
unless configuration.json_engine
raise MissingConfigurationError.new("configuration.json_engine has not been set")
end
MultiJson.engine = configuration.json_engine
Faraday.new("http://#{configuration.host}:#{configuration.port}") do |builder|
builder.use Silo::Client::Middleware::APIVersioning
builder.request :json
builder.use Faraday::Response::Mashify.tap { |m| m.mash_class = FrozenMash }
builder.use Silo::Client::Middleware::ParseJSON
builder.use Silo::Client::Middleware::RaiseError
builder.adapter configuration.http_lib || Faraday.default_adapter
configuration.middleware_blocks.each do |block|
block.call(builder)
end
end.tap do |conn|
conn.basic_auth(configuration.username, configuration.password)
end
end
end
class Configuration
attr_accessor :host,
:port,
:username,
:password,
:http_lib,
:feed_delay,
:json_engine,
:subscription_namespace,
:api_version,
:hmac_access_id,
:hmac_secret_key
def initialize
self.api_version = 1
end
def middleware(&block)
middleware_blocks << block
end
def middleware_blocks
@middleware_blocks ||= []
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment