Ruby 生成辅助函数模块
我正在编写一个DSL来为生物信息学平面文件生成解析器。我想让用户在块中定义helper函数,然后在解析上下文对象中包含该函数。我想使用如下语法: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
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
方法没有什么特殊功能,但它只是依赖于规则
块已经是当前范围这一事实