Scaffolds for free
Friday, 25 April 2008One of the novel concepts introduced to the mainstream by Ruby on Rails was that of scaffolding.
Using as many acronyms as possible, the idea was that to DRY with CRUD functionality. Rails achieved this with the helper method #scaffold.
Django, among other web frameworks, realized that specifying #scaffold at the beginning of cookie-cutter controllers isn’t exactly DRY. Nor is implementing an authentication and user management system. Django, for one, offers a nice, modular Admin interface that can be turned on with a few lines of code.
Doing this in Rails isn’t easy. Rails Engines make it possible, but it’s still an extra step.
Merb, on the other hand, does play nice, though not obviously.
Building on the work I did with distributed MVC, as well as the proof-of-concept exception logger MeX, I took a look into creating a Merb Plugin / Gem that will automatically provide scaffolding for free for all models in a Merb app.
Merb AutoScaffold
The result is Merb AutoScaffold. Install the gem, require it in your app, and you’ll have scaffolding by default.
Here’s the way it works:
- Find all of the models
- For each model, create or extend it’s controller
- For each controller, add CRUD actions that don’t already exist
This is pretty straight forward, and made even more simple with some helpful Merb methods.
For one, Merb keeps track of load paths with Merb.dir_for. Also, the Merb::Controller#_template_location makes it easy to hijack where templates are loaded from.
The trickiest part with the gem is making sure to give precedence to parts of the application that already exist – you don’t want scaffolding to override locally defined methods.
Update – April 27 – It ends up that it’s nice to keep the admin interface separate from the regular interface. Thus, AutoScaffolds have been updated to be namespaced. So, for example, when AutoScaffolds creates a controller for the Blog model, it will create Scaffold::Blogs < Application so as not to conflict with already existing controllers. Likewise, this will map to the /scaffolds/blogs path by default, though the route namespace can be configured in init.rb.
Right now the gem is at a 0.1.0 release. It could look a lot prettier, have better support for ID and Date fields, and ideally will have support for associations in the future. But for the time being, it’s as pretty at merb-gen resource’s scaffolds, and gets the job done. Who could ask for more?
UPDATE – April 27th – 0.1.2 has just been released, bringing with it support for associations, merbivore.com-type styling, namespacing, and pagination (in edge). Once tests are complete, version 0.2 should be ready for release as a full-fledged gem!
Comments
Comments are closed