Create a gist now

Instantly share code, notes, and snippets.

shared global ruby configuration dsl example
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