问题
I'm trying to save the previous URL in a session, I currently have this code:
after_filter "save_my_previous_url", only: [:renderForm, :renderQuote]
def save_my_previous_url
if URI(request.referer).path
session[:my_previouse_url] = URI(request.referer).path
else
session[:my_previouse_url] = URI(request.referer).path
end
end
It works when you go from a page, to the form, then to the thank you page, but if you go straight to a form directly instead of clicking a link, I get this error:
bad argument (expected URI object or URI string)
So I need to some how ignore this when there isn't a previous url.
回答1:
Well, I'll share a little technique I always use with ruby/rails when dealing with null or empty objects/variables.
def save_my_previous_url
if request.referer.present?
session[:my_previouse_url] = URI( (request.referer || "") ).path
else
session[:my_previouse_url] = URI( (request.referer || "") ).path
end
end
Explanation: The technique here is to assume that in the worse case scenario, we return nil from the method call request.referer. So, whenever you are passing a null value into a function and know that the next method call will blow up, pass this snippet as the argument:
( @variable || "whatever_value_needed" )
#alternatively:
( method_call || "whatever_value_needed" )
In this case the "whatever_value_needed" should be an empty string.
This technique works because the request.referer method call first gets evaluated to nil, more specifically a boolean false. Then, due to the 'or' || operator, the second operand is evaluated, which in this case is "". The URI object instantiation then runs smoothly because it accepts an empty string as an argument, and all method calls on this new object will work(...not throw an exception).
Feel free to utilize this technique wherever you run into this problem. If this helped you, please upvote!
回答2:
You need to make sure that you handle both nil referrer and referrer's who URLs can't parse (e.g. urls like http://x.com?utm_term=a|b -- "|" causes the parsing to fail, at least in some versions of rub).
This code (or something like it) works for me:
begin
if request.referer.present? && URI.parse(request.referer).path
session[:my_previouse_url] = URI(request.referer).path
else
session[:my_previouse_url]=nil;
end
rescue URI::Error => e
session[:my_previouse_url]=nil;
end
来源:https://stackoverflow.com/questions/17148470/ignore-urirequest-referer-path-for-previous-url-when-visiting-directly-to-a-pa