【问题标题】:rails - DRY up controller actionsrails - 干燥控制器动作
【发布时间】:2012-07-08 13:58:28
【问题描述】:

我有一个有很多重复代码的控制器,例如:

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 变脏并允许其他控制器调用我的操作。

有解决代码重复问题的想法吗?

【问题讨论】:

    标签: ruby-on-rails controller metaprogramming dry


    【解决方案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 返回一些消息以通知您是否有意义?

    【讨论】:

    • 感谢 jdoe,问题是调用“action1”控制器调用模型上的“action1”(并不总是相同的操作)。例如。有一个名为归档的操作,它调用@post.archive,它将归档我的帖子。无论如何,这解决了 custum 字符串的问题。我得到你的解决方案了吗?
    • @Andrea 没注意到。但是您可以像以前一样使用@post.send+params[:msg] 来实现它。只需确保恶意用户无法触发某些不允许的操作即可。
    • 嗯,我会探索这个解决方案!
    【解决方案2】:

    我不认为这个解决方案有什么太难看的地方。

    要将逻辑限制在一个控制器中,您可以在 PostController 中定义 self.action_for,而不是在 ApplicationController 中定义,并在其定义下方调用它。

    请注意,您已经将第一个元素作为符号成对传递,因此不需要在 action_for 中调用 to_sym。

    【讨论】:

    • 谢谢 dgutov,我想我会使用你的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2012-01-10
    • 1970-01-01
    • 2011-09-02
    • 2017-09-24
    相关资源
    最近更新 更多