Skip to content

Instantly share code, notes, and snippets.

@tompave
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tompave/6136d090efd82381c13d to your computer and use it in GitHub Desktop.
Save tompave/6136d090efd82381c13d to your computer and use it in GitHub Desktop.
Some configuration techniques in Ruby
module Foobar
module Config
class << self
attr_writer :foo, :bar, :baz
def foo(value = nil)
if value
self.foo = value
else
@foo
end
end
def bar(value = nil)
if value
self.bar = value
else
@bar
end
end
def baz(value = nil)
if value
self.baz = value
else
@baz
end
end
end
end
def self.config(&block)
if block_given?
if block.arity > 0
yield Config
else
Config.class_exec &block
end
else
Config
end
end
end
module Foobar
module Config
ATTRIBUTES = [:foo, :bar, :baz]
class << self
attr_writer *ATTRIBUTES
ATTRIBUTES.each do |attribute|
class_eval "def #{attribute}(value = nil)
if value
self.#{attribute} = value;
else
@#{attribute}
end
end", __FILE__, __LINE__+1
end
end
end
def self.config(&block)
if block_given?
if block.arity > 0
yield Config
else
Config.class_exec &block
end
else
Config
end
end
end
conf_module = Foobar.config
Foobar.config.foo = 1
Foobar.config do |conf|
conf.foo = "hello"
conf.bar = "good bye"
end
Foobar.config do
bar 42
baz 1337
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment