I am creating a web page where the user enters the name of a web site in a text box. The user submits this information and he is redirected to the web site. What I want to do is save the recently entered web pages and show them on the main page so that the user can directly click on them instead of entering them and clicking on submit. How can this be achieved using sessions/cookies? I also want to make sure that only those web sites are displayed in the list that were successfully loaded. So, if i type "dfasfa" in the text box, it should not be added to the list of recently visited sites.
Asked
Active
Viewed 33 times
1 Answers
0
You won't know if the page load on external site succeeded unless you try it yourself.
You could do something like:
require 'net/http'
require 'uri'
class LoadVerifier
def initialize(uri)
@uri = URI.parse(uri)
end
def loads?
# see how to perform a HEAD request using net/http
end
end
and in your controller:
def check_and_add
# make it an array if it isn't defined yet
session[:recent_urls] ||= []
if LoadVerifier.new(params[:url]).loads?
# add new one in the beginning so that latest is first:
session[:recent_urls].unshift params[:url]
# remove last one if we have over 10 already stored :
session[:recent_urls].pop if session[:recent_urls].size > 10
end
end

Kimmo Lehto
- 5,910
- 1
- 23
- 32
-
Is the first snippet a controller? I am new to Ruby and Ruby on Rails. – user3701075 Jun 17 '14 at 20:13
-
no, that was just something you would probably throw in lib/ or somewhere. second one was the controller. – Kimmo Lehto Jun 18 '14 at 10:24
-
Your question was: "How can this be achieved using sessions/cookies?", i might have overengineered it a bit. But the main point is that you can store an array in a session and just add the new items to that array. – Kimmo Lehto Jun 18 '14 at 10:36
-
Your comment (# see how to perform a HEAD request using net/http) was actually the most useful thing! Did a search and found this - http://stackoverflow.com/questions/8014291/making-http-head-request-with-timeout-in-ruby. Thanks. – user3701075 Jun 18 '14 at 16:59