I want to include this, for example:
jQuery(document).ready(function($) {
$(\'#my-modal\').modal(options)
});
In one specific place in
Late to the party, but for anyone viewing this today I think I've come up with something better.
Punchbox Gem for Rails
With this, you can write code like:
class Post {
controller() {
// Runs on every action
}
index() {
// Runs on just the index action
}
}
Punchbox.on('Posts', Post);
(You can also create an object instead of a class. See the docs)
I've written about this much more in depth here: https://kierancodes.com/blog/page-specific-javascript-in-rails-4
These are some useful tricks
your.js
for your javascript your.js
on specific your layout //= require_tree .
on application.js
your.js
to asset percompile on config/application.rb
: config.assets.precompile += %w( your.js )
put your js script with javascript tag on mymodal.html.erb
put your js script into layout/yourlayout.html.erb
and use if.. else..
logic.
example :
<% if current_page?(yourspecific_path) %> <script language="text/javascript"> your javascript here .. </script> <% end %>
Read more here about current_page?
Or use request.fullpath
to get current full path
example :
<% if request.fullpath == yourspecific_path %> <script language="text/javascript"> your javascript here .. </script> <% end %>
Read more here about request.fullpath
Also you can combine #1 and #3 if you want script put into file .js
cheers
jquery-readyselector is a plugin that "Extends $().ready()
to provide a convenient syntax for page-specific script"
Install jquery-readyselector
Create some CSS classes
<body class="<%= controller_name %> <%= action_name %>">
Scope your javascript to your page
$("#my-modal").ready(function() {
$('#my-modal').modal(options)
});
More info in this answer How to load page specific rails 4 js files?
Given the JS file you want to include is named my_modal.js
:
Place your JS
files placed in assets/javascripts
in some directory inside of
assets/javascripts
, for example application
.
Change line //= require_tree .
to //= require_tree application
in your application.js
(it prevents loading my_modal.js
on every page).
Place your my_modal.js
in assets/javasctripts
Add my_modal.js
to config.assets.precompile
array (config assets.precompile += ['my_modal.js']
) in your application.rb
.
Put javascript_include_tag 'my_modal'
in the view you want this file included
You can go to Rails guides for reference.
One of the solution is to insert our javascript in to its own file: Reference Link
For example :
// app/assets/javascripts/alert.js
alert("My example alert box.");
And including this file only in the view we want it to execute:
<%# app/views/page/contact.html.erb %>
<%= javascript_include_tag "alert" %>
<h1>Contact</h1>
<p>This is the contact page</p>
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 )