简体   繁体   English

在Rails中干燥response_to代码

[英]DRYing up respond_to code in Rails

I have several actions (lets call them action_a, action_b, etc.) 我有几个动作(我们称它们为action_a,action_b等)

In each action I want to check if the user is logged in and if not to have a respond_to block as follows 在每个操作中,我要检查用户是否已登录以及是否不具有respond_to块,如下所示

 format.js {
          if current_user.nil?
            render partial: 'some_partial', handler: [:erb], formats: [:js]
          end
        }

For one action this is fine, but not for many actions, as there will be many duplications of this code which will do exactly the same thing, it is not very pretty or maintainable 对于一个动作来说这是很好的,但对于许多动作来说却不是,因为此代码将有许多重复的动作可以做完全相同的事情,因此它不是很漂亮或无法维护

Is there a way to put this somewhere so I can reuse this code and not rewrite it in every needed action? 有没有办法将其放置在某处,以便我可以重用此代码,而不必在每个需要的操作中都重写它?

Use before_filter (rails <4.0) or before_action (rails 4.0) 使用before_filter(rails <4.0)或before_action(rails 4.0)

class YourController < ApplicationController
  before_filter :check_user

  ...
  your actions
  ...

  private
    def check_user
      redirect_to sign_in_path if current_user.nil?
    end
end

or if you want specific actions and respond use around_action (filter): 或者,如果您想要特定的操作并做出响应,请使用around_action(过滤器):

class YourController < ApplicationController
  around_action :check_user

  ...
  your actions
  def show
    @variable = Variable.last
  end
  ...

  private
    def check_user
      yield #(you normal action without js respond)
      format.js {
        if current_user.nil?
          render partial: 'some_partial', handler: [:erb], formats: [:js]
        end
      }
    end
end

Read up on Responders . 阅读响应者 These are meant to help with that. 这些是为了帮助您。

Your specific problem is what filters are generally used for. 您的特定问题是过滤器通常用于什么用途。 See this Section on Filters in the Action Controller Guide 请参阅《动作控制器指南》中有关过滤器的本节

More generally, this is just ruby code, so you can refactor everything out into methods: 更一般而言,这只是ruby代码,因此您可以将所有内容重构为方法:

def do_stuff_with(partial_name, format)
  if current_user.nil?
    render partial: partial_name, handler: [:erb], formats: [format]
  end
end


format_js { do_stuff_with('some_partial', :js) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM