2015-02-06 53 views
0

的陣列我有一個數組,看起來像這樣:instance_eval的特效

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

我有封裝在存儲在數組進程內對象的ActiveRecord查詢方法。我試圖找到一種方法把這個數組,然後調用它像這樣:

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

有人給我傳遞一個進程爲對象的技術,因此它得到該對象的環境中求:

Practice.instance_eval(&p) 

上面我們使用一元&將單個proc對象轉換爲一個塊,然後在實踐環境中進行評估。這很好。但是一系列Procs呢?試圖特效的陣列上使用&顯然是行不通的:

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

如果我嘗試將它們作爲一個塊Practice.instance_eval之前調用進程內對象,他們在原始定義的範圍內得到評估:

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

是否有另一種方法來獲得這些在實踐環境中評估的procs數組?

回答

1

看來我有它的方便降低(又名注入)方法的工作:

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