I’ve been playing with an idea lately that makes scaffolding a Merb app more pragmatic than the traditional generator method. I call it “Magic Scaffold for Merb”.

One of the problems I’ve always had with code generators is that they create several files with code all over the place that I’m not familiar with. Ideally, I’d like to start with one file that I can then change over time or cut/paste into separate files as desired. In addition, because I change my models around a lot near the beginning of an app (the time when generating code is most useful) I would like the generated code to be updated almost constantly to reflect my experiments with the data model.

Magic Scaffold for Merb accomplishes these tasks by doing a little bit of clever work for you. First, rather than being a command-line code generator, Magic Scaffold is a method. You put it in a Merb controller and it gets called when the class itself is loaded. Second, it requires a Ruby block in curly braces. This is a little trick that takes advantage of the fact that in Ruby, blocks can be inspected to return the filename and line number at which they were declared. At this point, the Magic Scaffold code parses the ruby file where it was declared and inserts the scaffolding code wrapped inside a Ruby module. Finally, it reloads the ruby file so that the scaffolding code gets included, and then mixes the module into the controller. Presto, your controller is scaffolded.

The really nice part is that you can cut and paste any method from the scaffolded code (’index’, ’show’, ‘edit’, etc.) into the controller class (it must be above the magic_scaffold_here declaration) and the Magic Scaffold code will know not to try scaffolding that method any longer. As a result, you get the benefit of constantly re-scaffolded code with the flexibility of changing all or part of it as necessary.

Take a look at the Jing Demo and tell me what you think. The code is available in the lib folder of Marble’s code (part of the Merb repository).