Skip to content

Instantly share code, notes, and snippets.

@rtcoms
Created December 14, 2012 02:58
Show Gist options
  • Save rtcoms/4282273 to your computer and use it in GitHub Desktop.
Save rtcoms/4282273 to your computer and use it in GitHub Desktop.
require 'yaml'
# Simple loading of environment-namespaced config files with local overrides.
#
# LiteConfig(:foobar)
#
# loads and caches the current environment section from:
#
# config/foobar.yml
#
# The file must contain a yaml hash with environments for top-level keys.
#
# Config files can be overridden by adding _local to the filename:
#
# config/foobar.yml
#
# Local overrides are intended for individual developer boxes and thus
# should be left out of version control.
module LiteConfig
extend self
def fetch(name)
name = name.to_sym
@configs ||= {}
@configs.key?(name) ? @configs[name] : (@configs[name] = load(name))
end
private
def load(name)
filename = active_config_filename(name)
config = YAML.load_file(filename)[app_env]
raise "Oops, no #{app_env} config found for #{name} in #{filename}" unless config
config
end
def config_path
@config_path ||= File.join(app_root, 'config')
end
def config_filename(name)
File.join(config_path, name.to_s + '.yml')
end
def local_config_filename(name)
config_filename(name).gsub(/.yml$/, '_local.yml')
end
def active_config_filename(name)
File.exist?(local_config_filename(name)) ? local_config_filename(name) : config_filename(name)
end
def app_root
defined?(Rails) ? Rails.root : `pwd`.strip
end
def app_env
@app_env ||=
if defined?(Rails)
Rails.env
elsif ENV['RAILS_ENV']
ENV['RAILS_ENV']
elsif ENV['RACK_ENV']
ENV['RACK_ENV']
else
'development'
end
end
end
def LiteConfig(name)
LiteConfig.fetch(name)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment