Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

My generic Rails application.rb (See related posts)

(Updated Jun 2006.. please note this is wildly out of date!!)

This is the generic application.rb I use when starting most of my Rails projects:

class ApplicationController < ActionController::Base

	# Store the current URL so we can redirect back to it if necessary
	before_filter :store_locations


	# Store where we are
	def store_locations
		if @session['prevpage'] && @session['thispage'] != @request.request_uri
			@session['prevpage'] = @session['thispage'] || ''
			@session['thispage'] = @request.request_uri
		end
	end

	# Make sure the user is authorized. If not, make them log in.
	def authorize
		unless session[:user_id]
			redirect_to :signin_url
			return false
		end
		@user = User.find(session[:user_id])
	end

	# Make sure the user is authorized as an administrator. If not, make them log in.
	def authorize_as_admin
		unless session[:user_id] && session[:admin] == 1
			redirect_to :signin_url
			return false
		end
		@user = User.find(session[:user_id])
	end

	# Authorize the user if possible, but don't force it.
	def authorize_if_possible
		if session[:user_id]
			@user = User.find(session[:user_id])
		else
			@user = User.new
			@notloggedin = true
		end
	end

	# redirect_back
	# If a previous page is stored in the session, go back to it.. otherwise go back to a default page

	def redirect_back(default)
		if @session['prevpage'].nil?
			if default
				redirect_to default
			else
			 	redirect_to :controller => "", :action => ""
			end
		else
			if @session['prevpage'].length > 4
				redirect_to_url @session['prevpage']
			else
				redirect_to default
			end
		end
	end

end

Comments on this post

peter posts on Aug 04, 2005 at 18:58
And now I look at it, I should be changing those remaining non-symbolized parameters :)
joanofarctan posts on Aug 08, 2005 at 10:17
The authorize_as_admin method can be replaced with tidier Access Control, see This example or this one.
kitchen posts on Mar 08, 2006 at 09:39
shouldn't those functions you have defined to into app/helpers/application_helper.rb ? I realize they will work as they are, but I believe that's what the helper area is for ;)
peter posts on Jun 06, 2006 at 22:47
Please note this is wildly out of date and, well, 'wrong' :)

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts