Saturday, January 31, 2009

can_has_assets? A new Rails plugin for requiring stylesheets and javascript in views.

I sat down and scratched an itch I've had ever since I started developing Rails plugins: finding a way to require javascript / stylesheets on a per-view basis.

There's Needy Controllers, but that operates in your controllers, and me, being me, wanted to require the CSS and JS from the view, since I'm already hooked on the whole
<%= title "hello world" %>
in views idiom. (view-specific logic in views, basically)

So, I built can_has_assets as a way to scratch my itch. The master branch is currently acting as stable, and since the plugin is so simple, it probably won't be updated very often (or at all). Feel free to push if you do something interesting with it though.

Anyway, straight from the README:


CanHasAssets
============

can_has_assets is a super-simple way of requiring stylesheets and javascript files
from within views. It also supports inserting snippets of CSS and Javascript into
a page only once. Snippet support should really only be used for rapid prototyping,
though. :)

Installation
------------

script/plugin install git://github.com/radicaled/can_has_assets.git

Notes
-----

can_has_* will include a file or snippet only once -- it is safe to call these
methods multiple times, where-ever required.

Alternatives
------------

If you're looking for more control, consider Needy Controllers by Michael Bleigh:

http://github.com/mbleigh/needy-controllers/tree


Example
=======

In your layout:

<%= stylesheet_link_tag :can_has_assets %>
<%= javascript_include_tag :can_has_assets %>

In your views:

CSS
---
<% can_has_css 'css_file' %>

<% can_has_css :sample_snippet do %>
.item {
/* some fake example css here */
}

Javascript
----------
<% can_has_js 'js_file' %>

<% can_has_js :sample_snippet do %>
function helloWorld() {
alert("Hello, world!");
}
<% end %>

No comments: