Module: Tins::Interpreter

Included in:
Object
Defined in:
lib/tins/dslkit.rb

Overview

Provides dynamic code interpretation capabilities for evaluating string-based code within the context of an object instance.

This module enables the execution of Ruby code snippets as if they were blocks, maintaining access to the current binding and instance variables.

Examples:

Basic usage with automatic binding

class A
  include Tins::Interpreter
  def c
    3
  end
end

A.new.interpret('|a,b| a + b + c', 1, 2) # => 6

Usage with explicit binding

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

Instance Method Summary collapse

Instance Method Details

#interpret(source, *args) ⇒ Object

Interpret the string source as a body of a block, while passing *args into the block.

This method automatically creates a binding from the current context, making all instance variables and methods available to the interpreted code.

Parameters:

  • source (String, IO)

    The Ruby code to evaluate as a block body

  • args (Array)

    Arguments to pass to the interpreted block

Returns:

  • (Object)

    The result of evaluating the interpreted code

See Also:



282
283
284
# File 'lib/tins/dslkit.rb', line 282

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.

This method allows explicit control over the binding context, enabling access to specific local variables from a particular scope.

Parameters:

  • source (String, IO)

    The Ruby code to evaluate as a block body

  • my_binding (Binding)

    The binding object to use for evaluation

  • args (Array)

    Arguments to pass to the interpreted block

Returns:

  • (Object)

    The result of evaluating the interpreted code

See Also:



297
298
299
300
301
302
303
304
305
# File 'lib/tins/dslkit.rb', line 297

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