Monday, May 30, 2011

Managing coffeescript/js dependencies with the Rails 3.1 asset pipeline

We've been using and loving coffeescript and backbone on my current project.  In the last couple days we've upgraded our project to rails 3.1rc1 and been able to take advantage of the new asset pipeline therein.  This feature elegantly solves some super annoying problems we've had with managing dependencies in our app, but is not yet well documented.  I thought I'd take a few minutes and share what I've learned.

Where the assets live

Before rails 3.1, we'd lump all our javascript and stylesheets in the "junk drawer" that is public.  No more.  Now they can go in 3 different dirs depending on their purpose:

  • app/assets for things that our your application code
  • lib/assets for shared-ish things (not sure I grok what I'd put here yet)
  • vendor/assets to put things that your app uses but is provided by others
These directories are magically put on the asset pipeline for you.  In your views, you can reference things in any of these directories under the prefix /assets, eg. if foo.js was in app/assets (or lib or vendor) you would refer to it as /assets/foo.js.  The rails helpers such as javascript_include_tag will do this for you.

So this gives places to put stuff, which is nice, but only the beginning.  The killer features (for me) are the ability to package assets and manage dependencies.  To see how this works, take a look the app/assets/application.js file you get when generate a new rails 3.1 app.

Nothing but comments, weird huh. That's because this is what we're calling a "manifest file" which is basically just a file that requires in other files. When you include /assets/application.js at runtime, rails will package all the files you required and concatenate (and optionally minimize) them. Let's look at those last 3 lines, as there's magic in them thar comments. The first 2 require in jquery and jquery_ujs. It seems like this must mean that there are jquery.js and jquery_ujs.js files somewhere in one of the assets directories, but this isn't so. That's because gems can contribute to the asset pipeline as well. More on this later. The last line says to include all files in this directory or subdirectories as well.  In our apps so far we find it nice to have 2 such manifest files, vendor/assets/javascripts/vendor.js and app/assets/javascripts/application.js.  Not sure I can call this "best practice" or not yet, just that it seems nice to us so far.

It's also worth pointing out that files that need to processed (eg coffeescript and sass) will be handled automatically as well. Simply drop a file named whatever.coffee into the /app/assets directory and it will be compiled and included into application.js

Where this all gets more interesting to me is where we have files in the application that depend on each other. Files that are required can have requires of their own. The example I have in my app is coffeescript class inheritance. Imagine a couple classes like so:


When you're building apps with a lot of front end code, it's to be able to organize code with each class in it's own file. But this means you have to make sure to have the script that brings in fruit before apple. With the ability to require in rails 3.1, this problem is nicely solved for us. If we add a require statement to apple.coffee like so, the asset pipeline will take care of making sure things are in the correct order:

This is a huge win for me, as before this I was naming files with numbers such as 1_fruit.coffee to get around this problem. Yuck.

I mentioned earlier that I'd talk about assets living in gems.  This is a feature that allows you to take front end code and easily share it between multiple projects.  In my next post I'll talk about my experience building a rails 3.1 asset containing gem.

25 comments:

Rob Tarr said...

I was unaware of #=require for individual files. Thanks for pointing this out, it saved me a headache today.

-Rob

kt said...

I'm thinking about how to organize vendor/assets and app/assets and I was a little confused by what you mean by having two manifests. How does that work? Does one always get compiled before the other? What do they look like?

xinag zhong said...

These directories Buy rs gold are magically put on the asset pipeline for you. In your views, you can reference things in any of these directories under the prefix /assets, eg. if foo.js was in app/assets (or lib or vendor) you would refer to it as /assets/foo.js. The rails helpers such as javascript_include_tagCheapest Diablo 3 gold will do this for you.

summerlijia said...

Do you afraid of the doomsday? Stop worrying. Because it won't change anything; it just messes with your mind and steals your happy. If you feel nervous, do something to vex the presure. As for me, I prefer to playing D3 which is very interesting. But you need to buy diablo 3 gold to exchange the items. Finding a reliable store selling cheap diablo 3 gold is sometimes a question for me. I just hope you'll find a proper way for you to handle the negative feeling. Have a good day.

jerey ni said...

Let's face it, the double cyclone is a single-person gameplay.Diablo 3 Barbarians Guide When you play with and base faithful when you can provide in addition to the roar resistance is to run non-stop to maintain their Saiyan.
I decided to share the I barbarians program, this configuration you can pace, you can feel that you are a team and team. Diablo 3 Gold And, on my recent research program as I pursue some of the challenges and operations.

rscredits said...

Hey , what you say is really informative and funny, i like it and hope for more update.buy runescape gold

I think you just did a right thing to make this choice, rs gold you know that's really funny and i am sure you will not regret.One half of the world does not know how the other half lives

runescape gold

love supra said...

All's for the best in the best of all possible worlds! I have not see post good enough like yours here.Just admire your intelligence and informative explanation. I am a wow gamer but can't write such detailed info about that.
More tags: wow gold for cheap /
world of warcraft gold /
wow gold /
cheap wow gold

adeoe said...

I was unaware of #=require for individual files. Thanks for pointing this out, it saved me a headache today.
GW2 Gold

gautruc90 said...

I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement.


aion accounts

huong le said...

Thanks so much with this fantastic new web site. I’m very fired up to show it to anyone. It makes me so satisfied your vast understanding and wisdom have a new channel for trying into the world.


aeration services toronto

Hoai Pham said...



This article is very good, I like, today I want to introduce you to a very stylish bags, I believe you will like and I like these.

University of Phoenix Online

Bogayaen said...

I agree with your conclusions and will eagerly look forward to your incoming updates. Just saying thanks will not just be adequate, for the wonderful clarity in your writing.It is imperative that we read blog post very carefully

dallas teeth whitening

SteveMar22 said...

I enjoyed reading through your posting. I need to say that it was the 1st article on your blog I genuinely enjoyed and in which I had a feeling of agreement, know what I mean? In any case, keep the posting and I’ll be back once again.


moving companies sacramento

Chaelafe said...


Your article is simply fabulous. It’s got a lot of interesting information that is well-written, engaging and intelligent. Your ideas are very smart and fresh. Thank you for creating such unique content for your readers.

University of Phoenix Online

Chioero said...

This is a wonderful post. I will share it to everynone, It is great to have the opportunity to read a good article with useful information on topics that plenty are interested on. I will eagerly look forward to your future updates.
metal signs

floristmar23 said...

This is a wonderful orientating. I enjoyed the entropy lot. I noesis signification this authorised. Thanks for method this one connecter.

University of Phoenix Online

Katifka said...

I have to say i am very impressed with the way you efficiently website and your posts are so informative.

cheap moving companies in sacramento ca

peter james said...

Thank you, it's very brilliant information about this topic it might be very polite for students. Recently i needed resume writer "marvelousresume.com". To my admirable surprise, resume was worthy the price I paid for it.

fabricated acylic letters with led lighting

caton yesiondre said...

In its analysis from the present sector scenario, CNET noted that it is not a microsoft office 2010 activation key lot of that Home windows 8 is unappealing up to it really is which the OS finds by itself less than stress from other industry factors at do the job. As Dell have famous, for instance, there is certainly a general slowdown of windows 7 ultimate product key Computer development within the worldwide market place arena, which brings us to a painful reality the need for the OS, consequently, may also choose this sort of a slowdown.

love supra said...

Thanks. I always enjoy reading your posts - they are always humorous and intelligent.You can learn more: China tour packages | China travel packages | China Travel Agency

AntoL-Nyo said...

HD kaliteli porno izle ve boşal.
Bayan porno izleme sitesi.
Bedava ve ücretsiz porno izle size gelsin.
Liseli kızların ve Türbanlı ateşli hatunların sikiş filmlerini izle.
Siyah karanlık odada porno yapan evli çift.
harika Duvar Kağıtları bunlar
tamamen ithal duvar kağıdı olanlar var

somnus11258 said...

That is really cool. Thanks for finding it. Some really good ideas there, this is going to be a real time sink. I am a china tour lover,You can learn more: China tour packages | China travel packages | China Travel Agency

love supra said...

Welcome to the leading online Mandarin school that makes you fluent in a short time -- all from the comfort of your home or office!

I am a Chinese teacher,you can learn more about Free Chinese language info: Mandarin Chinese teacher | Online Chinese teachers | Native chinese teacher

AntoL-Nyo said...

Ben istanbuldan selda 22 yaşında konfeksiyon içşisiyim Amatör Porno sizleri bekletmeden hemen hikayeme geçiyorum.. Biz 5 katlı bir binanın en üst katında yaşıyorduk ve bir öğlen paydosunda sevgilim beni Anal Sikiş aradı evdeydim çünkü evle iş yerim arasında 2 dakika bile yoktu.. Bende Asyalı Porno sevgilime benden telefon beklemesini söyledikten sonra evin durumuna baktım evde kardeşlerim ve annemin Esmer Porno birkaçtane arkadaşı vardı bu iş imkansızdı tekrardan düşündüm ve çatı katı aklıma geldi sevgilime telefon açıp çatıya çıkmasını ve Fantazi Porno beni beklemesini söyledikten sonra telefonu bir süre elime almadım anneme işe gidiyorum dedikten sonra Gay Porno hemen üst kata çatıya çıkıp sevgilimin
dudaklarına yumuldum az bir süremiz Götten Sikiş vardı ve çok istiyordum onu hemen önünde diz çöküp sikini çıkardım kocaman olmuştu bile... Özlemişti beni HD Porno bitanem başladım sikini yalamaya kafasını öpüyor onu çıldırtıyordum sevgilim saçlarımdan tutmuş ağzımı keyifle sikerken çatı katının kapısı açıldı toparlanamadan Lezbiyen Porno komşunun şişman oğlu efecan gelmişti ben dizlerimin üzerinde sevgilimin Liseli Porno siki ağzımda yakalanmıştım hemen bu halimizi gören komşu oğlu Sarışın Sikiş kaçarcasına gitti.. Sevgilim bir süre güldükten Türbanlı Porno sonra bu şişko neden kaçtı korktu herhalde onu sikicem sandı galiba dedikten sonra bir kahkaha daha attı ben sevgilimin Türk Porno sikine deli gibi saldırıyor yalıyor emiyordum boşalmasını istiyor Zenci Porno sütünü içmek istiyordum sevgilim ağzımı sike sike boşaldı hepsini yuttum bir damlasını ziyan Porno etmedim ve sevgilimle vedalaşıp ayrıldık... Ben her defasında sikiş yapmadan önce yazporno diye olan türkçe siteden Porno izle bölümüne girip seyrediyorum azdıktan sonra şahane sikiş ile gözleri kamaştırıyorum.

Jessica Colin said...

Today is Violet Folklore’s 5th anniversary! It was on September 19th, 2008 that Sasha and I, after weeks of talking about how we’d work it all out, plunged forward and set up our Etsy account. We had met at a local herb class the previous year; I remember noticing Sasha right away on the first

smallbusinessnetworkingclub.com |

tricouhouse |

www.aspextechnology.org |

businessanalysissummit.com |

connecticuthomeenergysolutions |

http://www.emmrautoauction.org |

www.homefixcorporation.org |

lsw-ltd.co.uk |

pepsicollegecredit |