Specifically, I'm currently working on a Ruby on Rails app where I require this behavior, but I intentionally worded my title in a language and framework agnostic manner after realizing that a lot of the existing questions on SO refer to specific languages or frameworks. I'm hoping for some general suggestions/guidelines on how this may be solved/implemented in any language/framework.
Background:
The app under development is a Ruby on Rails app with a login page. After login, a certain route leads to a page where a (sort of feedback) form is displayed at the bottom. This form section can be focused using a URL fragment (I expect there is an anchor).
If the user is already logged in, following a URL to the route with the fragment already appended leads to the page with the form section focused.
However, I need a solution where a single crafted URL leads to the section irrespective of whether the user was initially logged in or not. If the user is not already logged in, the login page should be shown, and after successful login, the form section should be focused.
Asides, the URL will be included in an email.
However, the fragment is lost on redirect, as it appears that it is not sent to the server by the browser, and the redirect is performed server side using:
def after_sign_in_path_for(resource)
params[:redirect_path].presence || stored_location_for(resource)
end
Is there a good, simple, clean solution for this type of scenario that may be implemented in any language or framework?
While I do have a sort of solution for this currently, I'm not entirely happy with it as it seems like a bit of a hack. I'll post that as an answer below, hoping someone else can come up with a better solution.
Be warned: This is a bit of a hack, that I'm not very fond of.
Essentially what I do is append the fragment twice to the URL, once with the
#
urlencoded and as part of the query string, and once unencoded. This is to support both the cases where the user is not already logged in and is already logged in.On the server side, before redirecting to the login page, we capture the current URL, and later use it to redirect back. However, naturally, the captured URL doesn't contain the unencoded fragment, which will be withheld by the browser, however, the urlencoded fragment will be present. This can be decoded either before saving (immediately on capture) or before use later, on redirect. Essentially, what you have to do is replace the last occurrence of
%23
the URL encoded#
with an unencoded#
, and then, use that for redirection purposes. You may use a regex replace to do this. For example, I substituted/.*\K%23/
with'#'
in Ruby (see below).Example:
Ruby on Rails:
Hope this helps someone, but I'm still hoping there is a better way to do this.