hexct hexct - 1 month ago 12x
Ruby Question

Rails asset pipeline require from public folder?

Is this a good practice to require assets located under public folder? e.g. I have lots of javascript under public/mythirdparyjs folder and I want to make these javascript files available for only specific page, what will be the best way to do this?


Thirdparty js files should be in your vendor folder. Once you precompile them for production they will be then moved into your public folder automagically. To call certain files on specific pages you need to remove the require_tree directive and also pay attention to which files are called in your application.js asset file. At the bottom of every view page (html.erb) you can add the following to run only page specific js:

<%= content_for :javascript do %>
  <script type='text/javascript'>
<% end %>

Then in your application/layout view at the bottom before the closing body tag you should add:

<%= javascript_include_tag params[:controller] if Rails.application.assets_manifest.assets["#{params[:controller]}.js"] %>
<%=yield :javascript %>

This will then run any js on a page by page view basis and include any require statements for any files in the corresponding controller's js asset file.