28 June 2017
Last week I worked on an issue that required me to build a JavaScript widget as an unstyled route in our Rails backend app. The JS widget works as follows:
Here are a few things I learnt while building this little feature.
In the following example, the GenericController
will use the layout app/views/layouts/generic.html.erb
instead of the app/views/layouts/application.html.erb
layout file
class GenericController < ApplicationController
layout "generic"
...
end
Ref: 2.2.13.1 Specifying Layouts for Controllers
I was able to test a redirect that was triggered in my JS file by setting window.location.href
to the value http://examplesite.com
. Using RSpec, Capybara (used for feature/acceptance testing) and Poltergeist, I used the following:
expect(page).to have_current_path('http://examplesite.com', url: true)
Ref: have_current_path
The JavaScript widget redirects with parameters in the url, that looked something like:
http://examplesite.com?name=Batman&alias=Bruce&car=batmobile
It was easier than I thought to pass these queryParams along with a transitionTo
:
route.transitionTo('session.register', { queryParams: { name: 'Batman', alias: 'Bruce', car: 'batmobile' }});
Ref: Query Parameters with transitionTo
Redirecting if guests aren't authorised to view page. Stashing queryParams
object and pass it in transitionTo
.
beforeModelWrapper: function (route, args) {
var transition = args[0];
var userParams = transition.state.queryParams;
if (!route.get('guestAllowed') && !this.get('isAuthenticated')) {
this.set('backupTransition', transition);
transition.abort();
route.transitionTo('session.register', { queryParams: userParams });
return true;
}
}
Ref: Storing and Retrying a transition
That is all.