Skip to content

Instantly share code, notes, and snippets.

@volontarian
Created March 14, 2015 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save volontarian/3c23d04dffb2d59a3212 to your computer and use it in GitHub Desktop.
Save volontarian/3c23d04dffb2d59a3212 to your computer and use it in GitHub Desktop.
Conventional API Provider Host Setting by Environment Fallback and Alias Mapping
class ApiProviderHost
ENVIRONMENTS = [:development, :test, :staging, :production]
ALIASES = {
dev: :development, testing: :test, stage: :staging, show: :staging,
live: :production, prod: :production
}
FALLBACKS = {
development: [:development, :test, :staging, :production],
test: [:test, :development, :staging, :production],
staging: [:staging, :production],
production: [:production]
}
def initialize(provider, working_environment)
@provider = provider
@environment = working_environment.to_s.to_sym
end
def setting_namespace
"apis.providers.#{@provider}.hosts"
end
def environment
if ENVIRONMENTS.include?(@environment)
@environment
else
ALIASES[@environment] || raise(
NotImplementedError,
'Your environment is unknown. Please update alias mapping!'
)
end
end
def to_s
host = nil
FALLBACKS[environment].each do |provider_environment|
host = Setting["#{setting_namespace}.#{provider_environment}"]
break if host
end
unless host
raise(
NotImplementedError,
'The API provider does not support your environment!'
)
end
host
end
end
describe ApiProviderHost do
describe '#to_s' do
it 'behaves like this' do
provider = 'name_of_host'
Setting.defaults[
'home_page.apis.providers.name_of_host.hosts.development'
] = 'http://localhost:3001'
# no fallback or alias mapping needed
expect(
described_class.new(provider, 'development').to_s
).to be == 'http://localhost:3001'
# fallback to development
expect(
described_class.new(provider, 'test').to_s
).to be == 'http://localhost:3001'
# alias mapping needed
expect(
described_class.new(provider, 'dev').to_s
).to be == 'http://localhost:3001'
# alias not found
expect{
described_class.new(provider, 'unknown_environment').to_s
}.to raise_error(
NotImplementedError,
'Your environment is unknown. Please update alias mapping!'
)
# environment not supported by provider
expect{
described_class.new(provider, 'staging').to_s
}.to raise_error(
NotImplementedError,
'The API provider does not support your environment!'
)
end
end
end
# powered by https://github.com/huacnlee/rails-settings-cached/
Setting.defaults[
'apis.providers.volontariat.hosts.development'
] = 'http://localhost:3001'
Setting.defaults[
'apis.providers.volontariat.hosts.production'
] = 'http://Volontari.at' # currently down :-(
host = ApiProviderHost.new('volontariat', Rails.env).to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment