Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 生成辅助函数模块_Ruby_Metaprogramming_Dsl - Fatal编程技术网

Ruby 生成辅助函数模块

Ruby 生成辅助函数模块,ruby,metaprogramming,dsl,Ruby,Metaprogramming,Dsl,我正在编写一个DSL来为生物信息学平面文件生成解析器。我想让用户在块中定义helper函数,然后在解析上下文对象中包含该函数。我想使用如下语法: rules = Rules.new do helpers do def foo() #... end def bar( baz ) #... end end # Here come the parsing rules which can access both help

我正在编写一个DSL来为生物信息学平面文件生成解析器。我想让用户在块中定义helper函数,然后在解析上下文对象中包含该函数。我想使用如下语法:

rules = Rules.new do
  helpers do
     def foo()
       #...
     end
     def bar( baz )
       #...
     end
   end
   # Here come the parsing rules which can access both helper methods
 end
我想将helper方法添加到模块定义中,并将模块包含在实例中(只是实例而不是类)


你知道我怎样才能达到那个目标吗?语法稍有不同的答案也很受欢迎。

也许是这样的吧

class Rules
  def initialize(&block)
    instance_eval &block
  end

  def helpers
    yield
  end
end

Rules.new do
  helpers do
    def hi_world
      puts "Hello World!"
    end
  end

  hi_world
end
请注意,尽管这里的
helpers
方法没有什么特殊功能,但它只是依赖于
规则
块已经是当前范围这一事实