I want to include some Javascript functionality in a Haml view, but I don't want it inserted into every view. Do I have to put the Javascript file in public/javascripts or can I put it in app/assets/javascripts to keep it hidden from user, and still reference from within the haml view file?
How would you do both these options if they are possible?
If your javascript is small and dealy simple, I would suggest include javascript directly in the HAML:
Otherwise you should use asset pipeline. It makes sure that your javascripts are pre-processed, compressed and minified. It also helps to keep your javascripts well organized (e.g. separation between your scripts and vendor scripts) and easily testable (with testing frameworks like jasmine/jasminerice/evergreen). If you are new to asset pipeline, here is a good read =)
You should just use
if it's specific to one place, you should use
content_for
And then in your view
Include Directly
If you want the javascript included directly into the haml, you can use
:javascript
You can put this into a partial and then just render the partial to keep your views clean.
Reference It
If you want to just reference javascript and have the browser pull it in, you should use
javascript_include_tag
like always. Here, you'll need to make the javascript file a manifest, instead of requiring it into theapplication.js
manifest. Remember to add the manifest toconfig.assets.precompile
in your application.rb, according to http://guides.rubyonrails.org/asset_pipeline.html(in your haml):
(in config/application.rb):