簡體   English   中英

導軌-干燥控制器動作

[英]rails - DRY up controller actions

我有一個帶有很多代碼重復的控制器,例如:

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變得骯臟,並允許其他控制器調用我的操作。

有解決代碼重復問題的想法嗎?

您為什么不做一個會收到一些額外參數的動作,例如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返回某些消息以引起您的注意才有意義?

我認為此解決方案中沒有任何丑陋之處。

要將邏輯限制為一個控制器,可以在PostController中定義self.action_for而不是ApplicationController,並在其定義下方調用它。

請注意,您已傳遞第一要素成對符號,所以to_sym在電話action_for是沒有必要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM