Skip to content

Instantly share code, notes, and snippets.

@gerhard
Last active December 17, 2015 14:29
Show Gist options
  • Save gerhard/5624635 to your computer and use it in GitHub Desktop.
Save gerhard/5624635 to your computer and use it in GitHub Desktop.
require 'delegate'
require 'faraday'
class ApiClient < SimpleDelegator
def initialize(args = {})
args = defaults.merge(args)
@login = args.fetch(:login)
@password = args.fetch(:password)
super(connection) # api_client.get("/foo") will be delegated to connection
end
# you could make connection private,
# but I can see a number of situations where you will want to access it directly
#
# you could define this in the initializer as an args.fetch(:connection) default,
# but experience tells me that you will want VCR or Faraday stubs,
# mocks don't work well in this situation
def connection
# v https is a must !!!
@connection ||= Faraday.new("https://api.example.org/query", api_credentials)
# ^ every request will include the api_credentials
end
private
attr_reader :username, :password
def api_credentials
{
:usr => login,
:pwd => password
}
end
def defaults
{
:login => ENV['APIPROVIDER_LOGIN'],
:password => ENV['APIPROVIDER_PASSWORD'],
}
end
end
class ApiProvider
def initialize(login = nil, password = nil)
login ||= ENV['APIPROVIDER_LOGIN']
password ||= ENV['APIPROVIDER_PASSWORD']
@uri = Addressable::URI.parse("http://api.example.org/query")
@uri.query_values = {usr: login, pwd: password}
end
end
class ApiProvider
def initialize(args = {})
args = defaults.merge(args)
@login = args.fetch(:login)
@password = args.fetch(:password)
end
private
attr_reader :username, :password
def defaults
{
:login => ENV['APIPROVIDER_LOGIN'],
:password => ENV['APIPROVIDER_PASSWORD'],
}
end
end
@gerhard
Copy link
Author

gerhard commented May 22, 2013

The constructor should know about defaults, that's its job.

Structs are under-used in my opinion. I've released HStruct recently, it helps me a lot with simple data structures. Some benchmarks were surprising.

As for the @uri, it doesn't belong in the initialize. api_client.rb is what I'm thinking.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment