Module: DSLKit::Interpreter
Instance Method Summary collapse
-
#interpret(source, *args) ⇒ Object
Interpret the string source as a body of a block, while passing *args into the block.
-
#interpret_with_binding(source, my_binding, *args) ⇒ Object
Interpret the string source as a body of a block, while passing *args into the block and using my_binding for evaluation.
Methods included from InstanceExec
Instance Method Details
#interpret(source, *args) ⇒ Object
Interpret the string source as a body of a block, while passing *args into the block.
A small example explains how the method is supposed to be used and how the *args can be fetched:
class A
include DSLKit::Interpreter
def c
3
end
end
A.new.interpret('|a,b| a + b + c', 1, 2) # => 6
To use a specified binding see #interpret_with_binding.
210 211 212 |
# File 'lib/dslkit/polite.rb', line 210 def interpret(source, *args) interpret_with_binding(source, binding, *args) end |
#interpret_with_binding(source, my_binding, *args) ⇒ Object
Interpret the string source as a body of a block, while passing *args into the block and using my_binding for evaluation.
A small example:
class A
include DSLKit::Interpreter
def c
3
end
def foo
b = 2
interpret_with_binding('|a| a + b + c', binding, 1) # => 6
end
end
A.new.foo # => 6
See also #interpret.
232 233 234 235 236 237 238 239 240 |
# File 'lib/dslkit/polite.rb', line 232 def interpret_with_binding(source, my_binding, *args) path = '(interpret)' if source.respond_to? :to_io path = source.path if source.respond_to? :path source = source.to_io.read end block = lambda { |*a| eval("lambda { #{source} }", my_binding, path).call(*a) } instance_exec(*args, &block) end |