Kevin Marsh

Merb Asset Helpers

Merb, like Rails 2.0, sports some very flexible asset helpers. But Merb’s asset helpers bring a whole lot more to the table in terms of flexibility, speed, and features. Kinda like Merb itself.

Take js_include_tag. Sure, you can just throw it in your application layout and include some Javascript on every page like you would with Rails. You can even “bundle” all your Javascript assets. No, not manually. Merb is smart enough to give you the flexibility of separate files in development mode, but give you the extra speed boost in production mode. This is probably old news to a lot of Rails developers that haven’t been under rocks for the past year.

But, Merb gives us even more flexibility. What if you want to minify your Javascript? Merb supports asset bundler callbacks, which let you run some code after a bundle is created:


  Merb::Assets::JavascriptAssetBundler.add_callback do |filename|
    system("/usr/local/bin/yui-compress #{filename}")
  end

Pretty cool huh? Now, you could come close to this in Rails with something like PackR but it gets better:

If you’re the kind of web ninja who keeps their Javascript or CSS separated, it may be kind of cumbersome to figure out which assets you should be including and when. Not with Merb. Enter include_required_js and include_required_css. Throw these two methods in your application layout and you now have the flexibility to specify what Javascript or CSS files to include for what view. In the view. Where it makes the most sense:


  <!-- application.html.erb -->
  <html>
    <head>
      <%= include_required_js %>
      <%= include_required_css %>
    </head>
    <body>
      <!-- SNIP! -->
    </body>
  </html>


  <!-- list.html.erb (or any view or partial, really) -->
  <% require_js 'auto-complete' -%>

I can see this making a lot of sense for including something like Javascript auto-completion or calendar popups only on pages that actually require them. Which is a huge win for the other, say 90%, of your pages that don’t require the Javascript file to be present.

P.S. Props to the Merb team for creating clean and well-documented code that makes finding gems like this easy (and maybe even a little fun) to find.

Others' Comments

  1. James Coglan said on January 22, 2008 @ 08:48 PM:

    Hi Kevin, thanks for the link. Just wanted to point out that PackR is also available as a Rails-independant gem: gem install packr.

    Also, I've written another plugin called Holly, which acts as a javascript dependency manager for Rails projects. Basically, each script file declares its dependencies in comments, and Holly parses files you include with javascriptincludetag and automatically includes all their dependencies on the page in the correct order. I've not looked into Merb yet but thought the idea might be useful: http://blog.jcoglan.com/holly/

Your Comments

Your name:

Your email:

Your blog:

Your comment: