I want to do something like this in my asset pipeline:
application.js
//= require jquery
//= require jquery_ujs
//= require_tree ./includes
//= require global
<% if File.exists? "#{Rails.root}/assets/javascripts/#{params[:controller]}.js" %>
//= require <%= params[:controller] %>
<% end %>
<% if File.exists? "#{Rails.root}/assets/javascripts/#{params[:controller]}/#{params[:action]}.js" %>
//= require <%= params[:controller] %>/<%= params[:action] %>
<% end %>
Now this doesn’t work because the assets files cannot access params variable. Now is there a way to grab what the current controller action names are from the asset?
Or is the asset file precompiled for the whole project, rending this impossible?
You may be able to make this possible through some Tom Foolery, but I would recommend highly against it.
The reason I say so is because you want this js resource to be cacheable, and for that to be the case it really needs to be static. Customizing the asset based on what controller is being invoked is going to result in what is a potentially a lot of unique resources all of which should be identified, downloaded and cached separately. Noting that you have included what are obviously unchanging resources such as jQuery, and pondering the possibility that these would need to be downloaded over and over again, I think the point becomes clear this approach doesn’t work to well.
If what you are trying to do is customize the initialization of a view based on the controller/action, I would recommend including function definitions in the static js asset you are delivering that you can then invoke directly from the page.
Hope this helps.