How to make javascript_include_tag recursive?

Published on October 06, 2010

How to make javascript_include_tag recursive?

    I don’t know about you, but for a long time I wasn’t able to connect my js-files in batches.

    Let me remind you that Rails has a standard javascript_include_tag helper (: all,: recursive => true) that includes all files from public / javascripts. But I wanted to control this process. And here is what I got:

    <%= javascript_include_tag collect_js("jquery-1.4.2", "jquery.*", "lib/*, "application") %>

    By default, all * .js files are recursively connected to the specified templates, but this can be disabled:

    <%= javascript_include_tag collect_js("jquery-1.4.2", "jquery.*", "application", :without_recursion => true) %>

    Helper source code under cat

    def collect_js(*patterns)
      options = patterns.extract_options!.stringify_keys
      recursion = !options["without_recursion"] # with recursion by default
      patterns.collect do |pattern|
        scripts = collect_asset_files(File.join(RAILS_ROOT, 'public', 'javascripts'), pattern + '.js')
        scripts = scripts + collect_asset_files(File.join(RAILS_ROOT, 'public', 'javascripts'), pattern, '**', '*.js') if recursion

    Good luck