1

次のようなコードの重複が多いコントローラーがあります。

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 が汚れてしまい、他のコントローラーが自分のアクションを呼び出せるようになります。

コード重複の問題を解決するアイデアはありますか?

4

2 に答える 2

1

のような追加のパラメーターを受け取る単一のアクションを作成してみませんmsgか? 次に、組み込みの I18n サポートを利用できます。

def some_action
  @post = Post.find(params[:id])
  if @post.action(current_user)
    flash[:notice] = I18n.t("messages.#{params[:msg]}", default: "Wrong message type")
  else
    flash[:notice] = I18n.t("messages.problem")
  end
  redirect_to root_url
end

それとも@post.action、通知のために何らかのメッセージを返すことを許可するのが理にかなっているでしょうか?

于 2012-07-08T14:11:51.590 に答える
0

このソリューションには、あまりにも醜いものはないと思います。

ロジックを 1 つのコントローラーに限定するself.action_forには、ApplicationController の代わりに PostController で定義し、その定義の下で呼び出します。

to_sym最初の要素をペアでシンボルとして既に渡しているため、呼び出しはaction_for必要ないことに注意してください。

于 2012-07-08T14:09:45.833 に答える