Created
July 20, 2009 08:16
-
-
Save unnu/150202 to your computer and use it in GitHub Desktop.
Rails AppConfig inplementation for application configuration
This file contains hidden or 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
class AppConfig | |
instance_methods.each { |m| undef_method m unless m =~ /^__|is_a\?|empty?/ } | |
def initialize | |
@hash = Hash.new do |hash, key| | |
hash[key] = AppConfig.new unless @finalized | |
end | |
end | |
def method_missing(message, value = nil) | |
if message.to_s !~ /=$/ | |
@hash[message] | |
else | |
raise ArgumentError, 'Configuration has been finalized' if @finalized | |
@hash.store(message.to_s.gsub(/=$/, '').to_sym, value) | |
end | |
end | |
def finalize | |
@finalized = true | |
@hash.each do |key, value| | |
if value.is_a?(AppConfig) | |
if value.empty? | |
@hash.delete(key) | |
else | |
value.finalize | |
end | |
end | |
end | |
end | |
def empty? | |
@hash.empty? | |
end | |
def inspect | |
@hash.inspect | |
end | |
module Shortcut | |
def app_config | |
Rails.configuration.app | |
end | |
end | |
end | |
class Rails::Configuration | |
def app | |
@app ||= begin | |
after_initialize do | |
@app.finalize | |
['::ActiveRecord::Base', '::ActionController::Base', '::ActionView::Base', | |
'::ActionMailer::Base', '::ActionController::TestCase'].each do |klass_name| | |
klass = klass_name.constantize | |
klass.__send__(:include, AppConfig::Shortcut) | |
klass.extend(AppConfig::Shortcut) | |
end | |
end | |
AppConfig.new | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment