次のようなコードの重複が多いコントローラーがあります。
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 が汚れてしまい、他のコントローラーが自分のアクションを呼び出せるようになります。
コード重複の問題を解決するアイデアはありますか?