By now everyone has heard of Dr Nic’s Magic Models, the library which automagically creates your models, associations, and (some) validations in Rails. Real handy, especially when you want to get up and started right quick.
“Get up and started right quick.” What does that remind me of? Oh, yes. Camping.
The newest Camping gem, 1.4.149, recently hit _why’s gemserver. Try it out.
sudo gem install camping --source code.whytheluckystiff.net -y
(-y is shorthand for --include-dependencies)
New in this version, most notably, are migrations. There’s an explanation page on the Camping wiki called Marking Your Database Versions. Basically: create a class in the Models module, have it inherit from V # (like V 1.0), give it self.up and self.down. Just like a real migration. The examples, like blog.rb, have been updated to use migrations.
So where’s this going? Magic models in Camping. It requires a touch of hackery, but that’s quickly becoming the norm for faithful Errers. For the impatient, get the Magic Models version of the Camping blog and try it out. (Make sure you install Magic Models with step #1 below, though.)
Take a look at the Camping blog example again. Three and a half steps.
- sudo gem install dr_nic_magic_models
- Add require ‘dr_nic_magic_models’ under require ‘camping/session’
- Remove the model definitions. Delete these lines:
class Post < Base; belongs_to :user; end class Comment < Base; belongs_to :user; end class User < Base; end
- Add two hackery lines to Blog.create and change the Blog::Models::Post.table_exists? check to Blog::Models::SchemaInfo.table_exists?. Like this:
def Blog.create ActiveRecord::Base.metaclass.send(:alias_method, :old_class_name, :class_name) ActiveRecord::Base.meta_def(:class_name) { |table_name| old_class_name(table_name.sub(/^blog_/i,'')) } Camping::Models::Session.create_schema Blog::Models.create_schema :assume => (Blog::Models::SchemaInfo.table_exists? ? 1.0 : 0.0) end
That’s it. As you can see, this is easy to drop into any new Camping app you’re working on. Just remember to change blog_ in the class_name meta_def to the db prefix for your Camping app. And don’t forget the bug spray.
Chime in.