繁体   English   中英

instance_eval proc数组

[英]instance_eval an array of procs

我有一个看起来像这样的数组:

conditions = []
conditions << Proc.new { where(own_property: 1) }
conditions << Proc.new { where(case_enabled: true) }
conditions
 => [#<Proc:0x007fb4675acc10@(irb):4>, #<Proc:0x007fb4675a5640@(irb):5>] 

我将ActiveRecord查询方法封装在存储在数组中的proc对象中。 我试图找到一种方法来采用此数组,然后像这样调用它:

Practice.where(own_property: 1).where(case_enabled: true)

有人向我展示了将proc传递给对象以便可以在该对象的上下文中对其进行评估的技术:

Practice.instance_eval(&p)

上面我们使用一元&将单个proc对象转换为一个块,然后在Practice的上下文中对其进行评估。 这很好。 但是,一系列Procs呢? 尝试在proc数组上使用&显然不起作用:

Practice.instance_eval(&conditions)
TypeError: wrong argument type Array (expected Proc)

如果我尝试在将proc对象作为一个块传递给Practice.instance_eval之前调用它们,则会在其原始定义的上下文中对其进行评估:

Practice.instance_eval(&conditions.map(&:call))
NoMethodError: undefined method `where' for main:Object

是否有另一种方法可以在实践的上下文中评估这些过程?

看来我已经使用方便的reduce(aka inject)方法工作了:

conditions.inject(Practice) {|model, p| model.instance_eval(&p)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM