DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

My Generic Rails Application.rb

08.04.2005
| 15277 views |
  • submit to reddit
        <b>(Updated Jun 2006.. please note this is wildly out of date!!)</b>

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

Snippets Manager replied on Mon, 2012/05/07 - 2:13pm

Please note this is wildly out of date and, well, 'wrong' :)

Snippets Manager replied on Wed, 2006/03/08 - 10:38am

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 ;)

Snippets Manager replied on Mon, 2012/05/07 - 2:13pm

The authorize_as_admin method can be replaced with tidier Access Control, see This example or this one.

Snippets Manager replied on Mon, 2012/05/07 - 2:13pm

And now I look at it, I should be changing those remaining non-symbolized parameters :)