Created
September 15, 2009 16:09
-
-
Save dcparker/187412 to your computer and use it in GitHub Desktop.
Prerequisites for Rails. Simple way to test for prerequisites for a specific action, and redirect appropriately to fulfill each prereq if not fulfilled.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
########### | |
## File: app/controllers/application_controller.rb | |
class ApplicationController < ActionController::Base | |
around_filter :catch_prerequisite | |
private | |
def catch_prerequisite | |
need = catch :prerequisite_unmet do | |
yield | |
return nil | |
end | |
return redirect_to :action => need if need | |
end | |
def prerequisite(need) | |
if send(need.to_s + '?') | |
return true | |
else | |
throw :prerequisite_unmet, need | |
end | |
end | |
end | |
########### | |
## File: app/controllers/other_controller.rb | |
class OtherController < ApplicationController | |
def login | |
if params[:username] | |
session[:user] = User.find_by_username(params[:username]) | |
redirect_to :action => :settings | |
else | |
render :login | |
end | |
end | |
def settings | |
prerequisite :login | |
render :settings | |
end | |
private | |
def login? | |
return true if session[:user] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment