2013-08-29 34 views
0

我需要在我的主幹應用中爲json接收current_user的所有功能。所以杉杉想法是添加一些這樣想:SystemStackError - 堆棧級別太深:在ActiveRecord中使用元編程

def receive_user_abilities # we will return onty hash for works and tasks 
    w = Work.accessible_by(current_ability).map { |w| w = {type: 'Work', id: w.id}) } 
    t = Task.accessible_by(current_ability).map { |t| t = {type: 'Task', id: t.id}) } 
    render json: t + w # returs merged hash 
end 

但兩者都行特別是一樣的,我決定給用戶一些metaprograming魔術。所以我的解決方案是創建新的幫助器,將其包含到我的控制器,並將* arg傳遞給新創建的模塊(幫助器)方法。那就是:

module AbilitiesHelper 
    def receive_abilities_for *classes 
    classes.inject([]) { |res, klass| res + eval(klass.to_s.capitalize + '.accessible_by(current_ability).map { |element| element = ({type: ' + klass.to_s.capitalize + ', id: element.id }) }') } 
    end 
end 

,這裏是從控制器

def receive_user_abilities 
    render json: receive_abilities_for(:work, :task) # returs merged hash 
    end 

它基本上是相同的新的呼叫,但由於某些原因,我收到一條錯誤SystemStackError - stack level too deep:

在哪裏?錯誤

回答

1

也許這種方法會更容易?

def receive_abilities_for *classes 
    classes.inject([]) do |res, klass| 
    res + klass.accessible_by(current_ability).map do |element| 
     element = {type: klass.to_s, id: element.id } 
    end 
    end 
end 

並調用這樣的方式這個方法:

def receive_user_abilities 
    render json: receive_abilities_for(Work, Task) 
end 

而且,對我來說,receive_abilities_for方法並不元編程。元編程是在運行時定義新的方法和類(我可能會誤解)。

+0

你是對的,但使用它很有趣))你的方法是偉大的。謝謝 –

+1

也,**元素= {類型:klass.to_s,id:element.id} **行應替換爲** {類型:klass.to_s,id:element.id} ** – hedgesky

相關問題