[英]instance_eval an array of procs
I have an array that looks like this: 我有一个看起来像这样的数组:
conditions = []
conditions << Proc.new { where(own_property: 1) }
conditions << Proc.new { where(case_enabled: true) }
conditions
=> [#<Proc:0x007fb4675acc10@(irb):4>, #<Proc:0x007fb4675a5640@(irb):5>]
I have ActiveRecord query methods encapsulated in proc objects stored in an array. 我将ActiveRecord查询方法封装在存储在数组中的proc对象中。 I am trying to find a way to take this array and then invoke it like so:
我试图找到一种方法来采用此数组,然后像这样调用它:
Practice.where(own_property: 1).where(case_enabled: true)
Someone showed me the technique of passing a proc to an object so that it gets evaluated in the context of that object: 有人向我展示了将proc传递给对象以便可以在该对象的上下文中对其进行评估的技术:
Practice.instance_eval(&p)
Above we use the unary &
to convert a single proc object into a block, which then gets evaluated in the context of Practice. 上面我们使用一元
&
将单个proc对象转换为一个块,然后在Practice的上下文中对其进行评估。 This works great. 这很好。 But what about an array of Procs?
但是,一系列Procs呢? Trying to use
&
on an array of procs obviously does not work: 尝试在proc数组上使用
&
显然不起作用:
Practice.instance_eval(&conditions)
TypeError: wrong argument type Array (expected Proc)
If I try to call the proc objects before passing them as a block to Practice.instance_eval
, they get evaluated in context of their original definition: 如果我尝试在将proc对象作为一个块传递给
Practice.instance_eval
之前调用它们,则会在其原始定义的上下文中对其进行评估:
Practice.instance_eval(&conditions.map(&:call))
NoMethodError: undefined method `where' for main:Object
Is there another way to get these array of procs evaluated in context of Practice? 是否有另一种方法可以在实践的上下文中评估这些过程?
看来我已经使用方便的reduce(aka inject)方法工作了:
conditions.inject(Practice) {|model, p| model.instance_eval(&p)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.