我有很多的重复代码的控制器,如:轨道 - 干涸的控制器操作
class PostController < ApplicationController
def action1
end
...
def actionN
end
end
,基本上每个动作做这样的事情:
def action
@post = Post.find(params[:id])
if @post.action(current_user)
flash[:notice] = "#{custom string for this action}"
else
flash[:notice] = "Problem with your request"
end
redirect_to root_url
end
我想过ApplicationController中的一个方法,它接受一组符号并生成其他方法,例如:
def self.action_for(*args)
args.each do |method, string|
define_method method.to_sym do
@post = Post.find(params[:id])
if @post.send method.to_sym
flash[:notice] = string
else
flash[:notice] = "Problem with your request"
end
redirect_to root_url
end
end
end
并调用PostController中:
action_for [:action1, "Congratulations!"], [:action2, "Cool action!"] ..
我认为这个解决方案是丑陋的,它使ApplicationController的脏,并允许其他控制器打电话给我的行动。
任何想法来解决代码重复问题?
谢谢dgutov,我想我会用你的解决方案。 – Andrea 2012-07-08 14:53:18