Customizing the Ruby on Rails scaffold
I’m trying to learn Ruby on Rails this week. I found a wonderful book called Learning Rails that takes a non-evangelical tone, works from the ground up, and seems to match my style pretty well (also, I love the errata). But I quickly ran into an issue not covered in the book, how do I customize the Ruby on Rails scaffold?
I wanted to customize the scaffold so that I could replace the space indents with tabs (I know, silly me) and add JSON support to the scaffold. I found a post about how to accomplish this in Rails 3, but my Mac and the book both talk Rails 2. So I dug in a little bit. Here’s what I came up with for doing this in Rails 2.2.2 on a Mac.
Copy the original Ruby scaffold folder to a new folder somewhere reasonable with the name
my_scaffold. (For the rest of these instructions you can replace
my with anything reasonable.)
% cp -R /usr/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/rails_generator/generators/components/scaffold /Users/myhome/Ruby/my_scaffold
Use a symbolic link to hook your new folder back to Ruby.
% ln -s /Users/myhome/Ruby/my_scaffold /usr/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/rails_generator/generators/components/.
Change the name of the generator script to reflect your folder name.
% mv /Users/myhome/Ruby/my_scaffold/scaffold_generator.rb /Users/myhome/Ruby/my_scaffold/my_scaffold_generator.rb
Edit the generator script to modify the name of the object it creates. Change
ScaffoldGenerator in the first line to
MyScaffoldGenerator (adjust that name as necessary).
Now you have your own scaffold. You can edit any of the templates in
/Users/myhome/Ruby/my\_scaffold/templates and use the command
ruby script/generate my\_scaffold MyObject my_field:string to get rolling.
Note, the stylesheet.css name still conflicts with the same file in the original scaffold. If you want to resolve that conflict you can edit another line in the generator script. The line
m.template('style.css', 'public/stylesheets/scaffold.css') would be made to refer to your new stylesheet name and the layout template should be changed accordingly. Notice that you don’t have to change the name of the actual
Fair warning, I am on day two of Ruby and Rails. I know almost nothing, so use the above hint with care. Feel free to comment if you know more and want to offer a better suggestion!