Friday, February 4, 2011

How to create Rails scaffolds and database tables dynamically


The idea I’m exploring here is whether or not we can build a CMS (content management system) in Ruby on Rails that can dynamically build a CMS. In other words, can we write Rails code that writes Rails code.
It seems we can. This is pretty awesome, and somewhat frightening, because it apparently works. Here’s a method in, say, a “utils_controller.rb”:
def generate_scaffold
@results = `script/generate scaffold
Things name:string value:string`
end
Note the use of backticks around the shell commands to generate a scaffold. If you run that method in your browser, it actually generates the controller, model, migration, etc.
Then do this:
def migrate
@results = `rake db:migrate`
end
Yep. Now you just migrated the database and have new “things” table.

No comments:

Post a Comment