我需要获得current_user的所有功能:json为我的骨干应用程序。所以第一个想法是添加一些这样的想法:
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
但两条线都特别相同,我决定使用一些元编程魔法。所以我的解决方案是创建新的帮助程序,将其包含在我的控制器中,并将* 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:
错误在哪里?
答案 0 :(得分: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 方法不是元编程。元编程是在运行时定义新的方法和类(我可能会弄错)。