在Ruby中对字符串和block求解

http://tech.ddvip.com   2008年01月18日    社区交流

内容摘要:对包含代码的字符串和block求解,是我最钟爱的Ruby特性之一。Ruby提供了多种不同类型的求解方式;不过我最常用的是下面这些:eval、instance_eval和class_eval。

  同样的脚本,可以在第二个上下文中执行;这个上下文返回当前正在散播的不同类型的赌博游戏。

class ContextTwo < DslContext  bubble :than, :is, :list, :the, :to, :more, :notify, :floor, :open, :brush
def announce
@stakes
end
alias open announce
def method_missing(sym, *args)
@stakes = sym
end
end

  正像我们看到的,添加新的上下文是非常方便的。由于DslContext的execute方法调用instance_eval方法,上面的代码可以如下的方式执行。

ContextTwo.execute(script) do |stakes|
puts ContextTwo.sym_to_stakes(stakes)
end

  为了使我们的示例更加完整,我们创建另外一个例子,显示所有接收通知的位置。

class ContextThree < DslContext  bubble :than, :is, :list, :the, :to, :more, :notify, :announce, :open,:open
def announce;
end
def open;
end
def brush(value)
:brush
end
def floor(value)
:floor
end
def method_missing(sym, *args)
true
end
end

  同样的,这个上下文也继承自使用了instance_eval的DslContext,因此,只要运行下面的代码来执行即可。

ContextThree.execute(script) do |positions|
puts positions
end

  在多个上下文中对DSL进行求解的能力,模糊了代码和数据之间的界线。可以对脚本‘代码’进行求解来生成报表(比如关于系统中已联系雇员的报表)。在展示需要多久才会新开扑克牌桌这样的上下文中,也可以对脚本进行求解(比如,业务规则说明需要15个人才能新开一张牌桌,系统知道在等待列表中有10个人,因此显示“5 more people needed before the game can start”)。使用instance_eval,我们可以在系统需要的任何上下文中,对同样的代码进行求解。

责编:豆豆技术应用

正在加载评论...