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

Displaying the last 10 pages visited from a session (See related posts)

I wanted to store and display an array of the last 10 visited pages in a session. With the help of some folks in #rubyonrails (particularly aqua) this is what i've come up with:


class ApplicationController < ActionController::Base
	before_filter :add_to_history
	before_filter :page_title
	
	def add_to_history
	  session[:history] ||= []
	  session[:history].unshift ({"url" => @request.request_uri, "name" => page_title })
	  session[:history].pop while session[:history].length > 11
	end


# This bit came from Peter Cooper's snippets source and was moved into the application controller:

	def page_title
		case self.controller_name
			when 'tag' 
				title = "Tags &raquo; " + @params[:tags].join(" &gt; ")
			when 'user'
				title = "Users &raquo; #{@params[:user]}"	 
			when 'features'
					case self.action_name
						when 'show' then title = "Feature &raquo; #{Feature.find(@params[:id]).title}"
						else title = APP_CONFIG["default_title"]
					end
			else 
				title = APP_CONFIG["default_title"] + self.controller_name + ":" + self.action_name
		end
	end
	helper_method :page_title

...
end


In your partial you might do something like this:


<h4>User History</h4>
<% for cur in session[:history][0..9] -%>
  <p><a href="<%= cur["url"] %>"><%= cur["name"] %></a></p>
<% end -%>



Feedback and comments would be appreciated

Comments on this post

sporkyy posts on Nov 14, 2005 at 03:55
I think this is brilliant, but I found a couple of areas for improvement.

I didn't like the addition of view-less actions, which really aren't things I want users to get back to. This is stuff like create, update and delete actions.

I didn't like duplicate entries either.

(I also renamed 'url' to 'uri' just because.)

def add_to_history
    session[:history] ||= []

    if File.exists?("#{RAILS_ROOT}/app/views/#{self.controller_name}/#{self.action_name}.rhtml") && session[:history].empty? || session[:history].first['uri'] != @request.request_uri
        session[:history].unshift({ 'uri' => @request.request_uri, 'name' => page_title })
        session[:history].pop while session[:history].length > 11
    end
end


I'm sure you can figure out what all that does.

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