1

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.

1 Answer 1

1

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

You just made my day ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.