简体   繁体   中英

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. 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:

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. This works great. But what about an array of Procs? Trying to use & on an array of procs obviously does not work:

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:

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)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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