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

Displaying The Last 10 Pages Visited From A Session

08.02.2005
| 7832 views |
  • submit to reddit
        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 » " + @params[:tags].join(" > ")
			when 'user'
				title = "Users » #{@params[:user]}"	 
			when 'features'
					case self.action_name
						when 'show' then title = "Feature » #{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

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

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.