Last active
August 29, 2015 14:01
-
-
Save tompave/6136d090efd82381c13d to your computer and use it in GitHub Desktop.
Some configuration techniques in Ruby
This file contains 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 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 |
This file contains 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 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 |
This file contains 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
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