Skip to content

Instantly share code, notes, and snippets.

@andrew
Created April 21, 2009 09:51
Show Gist options
  • Save andrew/99052 to your computer and use it in GitHub Desktop.
Save andrew/99052 to your computer and use it in GitHub Desktop.
# from http://www.insiderpages.com/rubyonrails/2007/01/get-referring-search-engine-keywords.html
def setup_referring_keywords
# Check whether referring URL was a search engine result
referer = @request.env["HTTP_REFERER"]
unless referer.nil_or_empty?
search_referers = [
[/^http:\/\/(www\.)?google.*/, 'q'],
[/^http:\/\/search\.yahoo.*/, 'p'],
[/^http:\/\/search\.msn.*/, 'q'],
[/^http:\/\/search\.aol.*/, 'userQuery'],
[/^http:\/\/(www\.)?altavista.*/, 'q'],
[/^http:\/\/(www\.)?feedster.*/, 'q'],
[/^http:\/\/search\.lycos.*/, 'query'],
[/^http:\/\/(www\.)?alltheweb.*/, 'q']
]
query_args =
begin
URI.split(referer)[7]
rescue URI::InvalidURIError
nil
end
search_referers.each do |reg, query_param_name|
# Check if the referrer is a search engine we are targetting
if (reg.match(referer))
# Create a globally scoped variable (@referring_search) containing the referring Search Engine Query
unless query_args.nil_or_empty?
query_args.split("&").each do |arg|
pieces = arg.split('=')
if pieces.length == 2 && pieces.first == query_param_name
@referring_search = CGI.unescape(pieces.last)
return true
end
end
end
return true
end
end
end
true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment