Imagine you have 2 pages in your application (landing and contact) and need an alert box to show up on the contact page only. How would you do it?
Traditionally, if it’s something small, you might bite the bullet and just include it in the view template:
And including this file only in the view we want it to execute:
And don’t forget to include your new file in the list of files to be compiled:
# config/environments/production.rb config.assets.precompile += %w( alert.js )
The solution I’ve found the most elegant requires adding CSS classes to the layout’s body tag and using the jquery-readyselector plugin.
First, in order to scope the pages through CSS selectors, let’s add some classes to our layout:
<%# app/views/layouts/application.html.erb %> <body class="<%= controller_name %> <%= action_name %>"> <%= yield %> </body>
contact page action was inside a controller named
PagesController, the rendered result would be the following:
<body class="pages contact"> ... </body>
Add this small bit of javavascript code to a new file:
Include the new plugin in the
application.js manifest file:
... //= require jquery //= require jquery_ujs //= require turbolinks //= require jquery-readyselector //= require_tree .
Because this file is picked up with the
//= require_tree . line in the
application.js manifest, there’s no additional step to load the asset. And that’s it! Your fancy alert box will now only run on your contact page.
Let me what you think of this solution and if you’ve come across this issue before. I’d love to hear about other solutions!