Last active
August 29, 2015 14:05
-
-
Save carlosantoniodasilva/99c63b691b2b893ca3b9 to your computer and use it in GitHub Desktop.
Deep config test
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
require 'active_support/all' | |
class RailsConfig | |
class Options < ActiveSupport::OrderedOptions | |
def initialize(value = nil) | |
value.each_pair { |k, v| set_value k, v } if value.is_a?(Hash) | |
end | |
def method_missing(meth, *args) | |
if meth =~ /=$/ | |
key = $`.to_sym | |
value = args.first | |
set_value key, value | |
else | |
self.fetch(meth) { super } | |
end | |
end | |
private | |
def set_value(key, value) | |
if value.is_a?(Hash) | |
value = self.class.new(value) | |
end | |
self[key] = value | |
end | |
end | |
def initialize | |
@options = ActiveSupport::OrderedOptions.new | |
end | |
def method_missing(meth, *args, &block) | |
if meth =~ /=$/ | |
key = $`.to_sym | |
value = args.first | |
if value.is_a?(Hash) | |
value = Options.new(value) | |
end | |
@options[key] = value | |
else | |
@options.fetch(meth) { @options[meth] = Options.new } | |
end | |
end | |
end | |
config = RailsConfig.new | |
config.payment_processing.schedule = :daily | |
config.payment_processing.retries = 3 | |
config.resque = { timeout: 60, inline_jobs: :always } | |
config.super_debugger = true | |
config.zomg = { foo: { bar: { baz: 'lol' } } } | |
config.lol | |
puts config.payment_processing.schedule # => :daily | |
puts config.payment_processing.retries # => 3 | |
puts config.resque.timeout # => 60 | |
puts config.resque.inline_jobs # => :always | |
puts config.super_debugger # => true | |
puts config.zomg.foo.bar # => { baz: 'lol' } | |
puts config.zomg.foo.bar.baz # => 'lol' | |
puts config.lol # => {} | |
# puts config.zomg.lol.raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment