Skip to content

Instantly share code, notes, and snippets.

@jrhorn424
Forked from zimbatm/config_dsl.rb
Last active August 29, 2015 14:08
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 jrhorn424/84153ace43c39de61271 to your computer and use it in GitHub Desktop.
Save jrhorn424/84153ace43c39de61271 to your computer and use it in GitHub Desktop.
# 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