2011-12-06 13:51:56 -05:00
|
|
|
require "docile/version"
|
2011-12-06 15:05:31 -05:00
|
|
|
require "docile/fallback_context_proxy"
|
2011-12-06 13:51:56 -05:00
|
|
|
|
|
|
|
module Docile
|
2011-12-06 14:46:46 -05:00
|
|
|
# Executes a block in the context of an object whose interface represents a DSL.
|
|
|
|
#
|
2011-12-06 15:05:31 -05:00
|
|
|
# Example of using an Array as a DSL:
|
2011-12-06 18:46:14 -05:00
|
|
|
#
|
|
|
|
# Docile.dsl_eval [] do
|
|
|
|
# push 1
|
|
|
|
# push 2
|
|
|
|
# pop
|
|
|
|
# push 3
|
|
|
|
# end
|
|
|
|
# #=> [1, 3]
|
2011-12-06 14:46:46 -05:00
|
|
|
#
|
2012-10-29 15:24:37 -04:00
|
|
|
# @param dsl [Object] an object whose methods represent a DSL
|
|
|
|
# @param block [Proc] a block to execute in the DSL context
|
|
|
|
# @return [Object] the dsl object, after execution of the block
|
2013-03-31 23:27:12 -04:00
|
|
|
def dsl_eval(dsl, *args, &block)
|
2011-12-06 14:46:46 -05:00
|
|
|
block_context = eval("self", block.binding)
|
2011-12-06 15:34:46 -05:00
|
|
|
proxy_context = FallbackContextProxy.new(dsl, block_context)
|
|
|
|
begin
|
2011-12-06 16:21:11 -05:00
|
|
|
block_context.instance_variables.each { |ivar| proxy_context.instance_variable_set(ivar, block_context.instance_variable_get(ivar)) }
|
2013-03-31 23:27:12 -04:00
|
|
|
proxy_context.instance_exec(*args,&block)
|
2011-12-06 15:34:46 -05:00
|
|
|
ensure
|
|
|
|
block_context.instance_variables.each { |ivar| block_context.instance_variable_set(ivar, proxy_context.instance_variable_get(ivar)) }
|
|
|
|
end
|
2011-12-06 14:46:46 -05:00
|
|
|
dsl
|
|
|
|
end
|
|
|
|
module_function :dsl_eval
|
2011-12-06 13:51:56 -05:00
|
|
|
end
|