Search code examples
ruby-on-railsrubyruby-on-rails-3dryrespond-to

DRYing up respond_to code in Rails


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?


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