Module: Tins::Interpreter
- Included in:
- Object
- Defined in:
- lib/tins/dslkit.rb
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.
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 Tins::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.
123 124 125 |
# File 'lib/tins/dslkit.rb', line 123 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 Tins::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.
145 146 147 148 149 150 151 152 153 |
# File 'lib/tins/dslkit.rb', line 145 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 |