Rails JavaScript and CSS file AutoInclude Snippet
Ok so you have a Rails application and it’s growing fast. Your putting complex logic where it belongs, Your partials are DRY, and your using TDD and BDD concepts in your project. The world is yours, your code is bullet poof. Well what about those pesky JavaScript and CSS files? If you have a lot of them they can easily get out of hand and become redundant and duplication becomes a direct result. So how can you DRY it up a bit you ask? With an asset_autoinclude_tag helper. The concept is simple. For each controller/view in your app you design a javascript and or css file with code directly related to the pages rendered by them. In addition to this you name them using the same Rails naming convention as your other files. For instance you have a PublicController you would create a public.css and or public.js file for any css/js code related to that controller. Everything else can go into application.js and application.css.
Heres the code.
Update:
I have moved this into a gem if you would like to use it in your projects. It’s available in my GitHub repository.
git clone git://github.com/timmatheson/asset_autoinclude_helper.git
You can also install the gem by adding GitHub to your gem sources and installing it.
INSTALLATION gem sources -a http://gems.github.com sudo gem install timmatheson-asset_autoinclude_helper-0.1.0
Then to include it in your application just call it in your global layout like this.
<%= asset_autoinclude_tag %>
You can also pass in options for the javascript_include_tag like :cache => true
<%= asset_autoinclude_tag(:cache => true) %>
And thats it. I hope this helps you dry up your code a bit. I know I am probably not the first one to think of this. I plan to make it into a gem soon so check back.
Best regards,
Tim Matheson