Laurent
Laurent

Reputation: 2178

Rails Assets Pipeline load JavaScript from controllers and methods

I want to stay DRY in my code so I want to auto-load my javascripts file when it matches a controller or/and a method and the .js exists. I added this to my layout

= javascript_include_tag params[:controller] if ::Rails.application.assets.find_asset("#{params[:controller]}.js")
= javascript_include_tag "#{params[:controller]}/#{params[:action]}" if ::Rails.application.assets.find_asset("#{params[:controller]}/#{params[:action]}.js")

So now when I add javascripts/my_controller/my_method.js it automatically loads it, which's nice.

Sadly I must add another line to precompile the asset otherwise an error is thrown (which says I must precompile my .js file) and I didn't find any way around this.

Rails.application.config.assets.precompile += %w( orders/checkout.js )

Does anyone has a solution to avoid tu add manually elements in this configuration ?

NOTE : I already tried to use require_tree . which was just loading all the files on every page and was not working in my case.

Upvotes: 1

Views: 74

Answers (1)

Anthony E
Anthony E

Reputation: 11245

You can use a wildcard to allow all JS files included in your views to be precompiled:

config.assets.precompile << '*.js'

Upvotes: 1

Related Questions