{{{
Do you remember “when we were writing a reusable sidebar element”:http://nicksda.apotomo.de/2010/11/lets-write-a-reusable-sidebar-component-in-rails-3/ some time ago? The sidebar used in many controllers was implemented using a “cell”:https://github.com/apotonick/cells which encapsulated both assets and code in one place. Those were good times.
When needed, we could render the box with a @render_cell@ call anywhere in our app.
#sidebar = render_cell :posts, :recent
h3. Reusability With Engines
Now, imagine this sidebar box was so universally usable that you wanna use it in another project. Code is usually distributed with gems in a Ruby environment – but how does that work with partials, helpers, view code?
We got engines in Rails. We got Cells. We got gems. So let’s pack the cell in an engine gem!
“Engines”:http://railscasts.com/episodes/277-mountable-engines were designed to distribute controllers, views and models between Rails projects. As an example, lots of the authorization gems around use engines for reusable login pages or password reset forms that can be used right in your project. There was no easy way for reusing partials and behaviour, though, unless you’re using cells.
h3. The Cell, Gemified.
In order to ship the sidebar posts box I first need to create a Rails engine.
$ rails plugin new sidebar --mountable
This creates a distributable directory with all the files needed to mount it into a Rails app.
As a second step we need to move the @PostsCell@ into that gem.
$ mv app/cells/posts sidebar/app/cells/
You can now include the @sidebar@ gem in any application using the @Gemfile@.
gem 'sidebar', :path => 'vendor/plugins/sidebar'
To render your reusable component, just use the @render_cell@ call as you did in the originating application.
h3. Conclusion
Damn, this conclusion came fast, but there is really not more to say. Oh, did I mention that you should update to Cells 3.8.3 for full engines support in Rails 3.0, 3.1 and even 3.2?!
Cells + Engines bring real reusability to Rails. It’s da shit.
}}}
Hi, does the engine need to be mountable ?
LikeLike
very impressive,thanks for your explain
LikeLike
Nice Nick, but pay attention, … vendoring is deprecated and will be removed in Rails 4.0
Will that works anyway ?
LikeLike