簡體   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