Save the file as /vendor/assets/javascripts/viewname.js
and include it in your view with:
<%= javascript_include_tag 'viewname' %>
To include the JS file in the HTML header
Use content_for
in a view file to collect content that will be rendered later.
<% content_for :head %>
<%= javascript_include_tag 'viewname' %>
<% end %>
Call yield
in the layout template to render the collected content:
<head>
...
<%= yield :head %>
</head>
To automatically include a javascript file named after the current controller, you could also put this in your layout template file:
<head>
...
<%= javascript_include_tag params[:controller] %>
<%= javascript_include_tag "#{params[:controller]}_#{params[:action]}" # variant with action name %>
</head>
But that will give 404 errors for a controllers/actions without a javascript file.