Question

I have several actions (lets call them action_a, action_b, etc.)

In each action I want to check if the user is logged in and if not to have a respond_to block as follows

 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?

Était-ce utile?

La solution

Use before_filter (rails <4.0) or 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):

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

Autres conseils

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:

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) }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top