连接 proc,同时保留上下文重新评估功能

Concatenate procs while retaining context reevaluation capabilities

我想连接两个过程的主体。但与 here 不同的是,这里有一个转折点。生成的过程应该保留原始过程的 instance_eval-ability.

这听起来可能有点令人困惑,所以这是我的用例。


我正在 Ruby 中实现另一种语言作为内部 DSL。过于简化的实现:

class Interpreter
  def self.run(&program)
    Interpreter.new.instance_eval(&program)
  end

  def initialize
    @variables = {}
  end

  def assign_variable(name, value)
    @variables[name] = value
  end

  def display(name)
    puts @variables[name]
  end
end

Interpreter.run do
  assign_variable :foo, 42
  display :foo
end

如果我将 proc 的主体分成另外两个:

assignment = proc { assign_variable :foo, 42 }
printing   = proc { display :foo }
combined   = proc { assignment.call; printing.call }

Interpreter.run(&combined)

它不会工作,因为 combined proc 正在 instance_eval-ed,但是 assignmentprinting proc在定义它们的地方的上下文中进行评估。

我想拆分原始过程的原因是我可以 DRY 我的测试。

你可以做到

combined = proc {
  instance_eval &assignment
  instance_eval &printing
}

但如果有人想出更惯用的东西,我不会感到惊讶