= BeforeActions {}[http://badge.fury.io/rb/before_actions]
Wiki[https://github.com/yakko/before_actions/wiki] | RubyGems[https://rubygems.org/gems/before_actions]
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
{}[https://github.com/yakko/before_actions]
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
{}[https://github.com/yakko/before_actions]
== 3. Nested Routes
Given that
Company has_many :clears
{}[https://github.com/yakko/before_actions]
== 4. Authorization made easy
{}[https://github.com/yakko/before_actions]
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.