【发布时间】:2014-03-14 18:23:47
【问题描述】:
这里的代码是对更大解决方案的简化。我试图弄清楚如何 制作一个可以很好地“读取”的 ruby DSL。第一个代码块;工作(现在工作) 我想知道如何编写 DSL
问题的核心在于,在处理类时,它没有可供我使用的实例变量。即:@match_code
有人知道更简单更优雅的解决方案吗?整个代码必须保存在一个类中。
我希望它看起来像:
class MatchStuff
include ProcessBase
match 'account' do | event |
pp event
end
end
matcher = MatchStuff.new
matcher.accept 'account'
当前工作(不是很好)代码
class ProcessBase
def initialize
@match_code = []
end
def match(string_match, &block)
@match_code.push([string_match, block])
end
def accept(test_str)
@match_code.each do | test_block |
if test_str == test_block[0])
test_block[1].call test
end
end
end
end
class MatchStuff < ProcessBase
def initialize
super
match 'account' do | event |
pp event
end
end
end
test = MatchStuff.new
test.accept 'account'
【问题讨论】:
标签: ruby metaprogramming dsl