-
-
Save jrhorn424/84153ace43c39de61271 to your computer and use it in GitHub Desktop.
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
# Encapsulate the configuration DSL pattern. | |
# | |
# Any `X=(value)` setter method on the given +obj+ is translated into `X(value)` method | |
# in the context of this object. | |
class ConfigDSL < BasicObject | |
def initialize(obj, &config) | |
@self = obj | |
call(&config) | |
end | |
# Calls the &config block in the context of self. | |
# | |
# If the arity of the block is == 1 then self is passed to the block rather | |
# than changing execution context to self. | |
def call(&config) | |
if config.arity == 1 | |
config.call(self) | |
else | |
instance_exec(&config) | |
end | |
end | |
# Forwards all naked methods as setter methods. | |
# | |
# Example: | |
# method_missing("foo", 3) tries to call @self.foo=(3) | |
def method_missing(method, *args, &b) | |
setter = "#{method.chomp ?=}=" | |
if args.size == 1 && @self.respond_to? setter | |
@self.__send__(setter, *args, &b) | |
else | |
@self.__send__(method, *args, &b) | |
end | |
end | |
# Because meta | |
def to_proc | |
method(:call) | |
end | |
end | |
if __FILE == $0 | |
class Foo | |
attr_accessor :a, :b, :c | |
end | |
foo = Foo.new | |
ConfigDSL.new(foo) do | |
a "333" | |
b 2452253425 | |
c a | |
end | |
p foo | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment