BeforeActions <img src=“” alt=“Gem Version” />

Wiki | RubyGems

BeforeActions an elegant way of loading resorces in your restful controllers.

Installation

In Rails 3 and Rails 4, add this to your Gemfile and run the bundle command.

gem "before_actions"

bundle

Run this command to make all your new generated scaffold controllers come with a before_actions call by default

rails g before_actions:install

Instructions

1. Using the command

<img src=“readme_images/method.png” alt=“image” />

class CleanersController < ApplicationController
  before_action :define_cleaner

  private
    # Use callbacks to share common setup or constraints between actions.
    def define_cleaner

      before_actions do
        actions                                  { # load your nested resource's parent here if you need one }
        actions(:index)                          { @cleaners = Cleaner.all                }
        actions(:new)                            { @cleaner  = Cleaner.new                }
        actions(:create)                         { @cleaner  = Cleaner.new(cleaner_params) }
        actions(:show, :edit, :update, :destroy) { @cleaner  = Cleaner.find(params[:id])  }
        actions                                  { # run your authorization logic here if you need one }
      end

    end

end

2. Enjoy your clean controller

<img src=“readme_images/clean_controller.png” alt=“image” />

3. Nested Routes

Given that

Company has_many :clears

<img src=“readme_images/nested.png” alt=“image” />

4. Authorization made easy

<img src=“readme_images/authorization.png” alt=“image” />

class CleanersController < ApplicationController
  before_action :define_cleaner

  private
    # Use callbacks to share common setup or constraints between actions.
    def define_cleaner

      before_actions do
        actions                                  { @company = Company.find(params[:company_id]) }
        actions(:index)                          { ... }
        actions(:new)                            { ... }
        actions(:create)                         { ... }
        actions(:show, :edit, :update, :destroy) { @cleaner  = @company.cleaners.find(params[:id])  }
        actions do
          if @company.manager == current_user
            flash[:alert] = "You need to be the manager for #{@company.name} to access this area."
            redirect_to root_path
          end
        end
      end

    end

end

This project rocks and uses MIT-LICENSE.