Created
April 7, 2011 19:13
-
-
Save colinsurprenant/908474 to your computer and use it in GitHub Desktop.
shared global ruby configuration dsl example
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
module App | |
module Global | |
extend self | |
def self.configure(&block) | |
instance_eval(&block) | |
end | |
def [](key) | |
config[key] | |
end | |
private | |
def set(key, value) | |
config[key] = value | |
end | |
def config | |
@config ||= Hash.new | |
end | |
def method_missing(sym, *args) | |
if sym.to_s =~ /(.+)=$/ | |
config[$1] = args.first | |
else | |
config[sym] | |
end | |
end | |
end | |
end | |
App::Global.configure do | |
set :a, 1 | |
end | |
class A | |
def test | |
puts("A: a=#{App::Global.a.inspect}") | |
puts("A: b=#{App::Global.b.inspect}") | |
puts("A: c=#{App::Global[:c].inspect}") | |
end | |
end | |
class B | |
App::Global.configure do | |
set :b, 2 | |
end | |
def test | |
App::Global.configure do | |
set :c, 3 | |
end | |
puts("B: a=#{App::Global[:a].inspect}") | |
puts("B: b=#{App::Global[:b].inspect}") | |
puts("B: c=#{App::Global.c.inspect}") | |
end | |
end | |
a = A.new | |
b = B.new | |
a.test | |
b.test | |
a.test |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment