代码之家  ›  专栏  ›  技术社区  ›  paradigmatic

生成助手函数模块

  •  0
  • paradigmatic  · 技术社区  · 16 年前

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

    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方法添加到模块定义中,并将模块包含在实例中(只是实例而不是类)。

    你知道我怎样才能达到这个目标吗?有稍微不同语法的答案也会受到赞赏。

    1 回复  |  直到 16 年前
        1
  •  1
  •   Ciarán Walsh    16 年前

    也许是这样?

    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 方法没有什么特别的,它只依赖于 Rules 块已经是当前作用域。

    推荐文章