May 05, 2010 00:31
Posted by Jeremy Durham
New gem - Seed
I pushed a new repository to Github and a new gem to Gemcutter. It’s called Seed.
Seed is (another) gem designed to deal with seeding databases.
The main advantage of using Seed is that when creating a seed, or retrieving a seed, an error is throw if you attempt to overwrite a seed or retrieve a non-existent seed. The goal is to make you care about your seed data, and ensure that you’re not overwriting existing seeds or trying to make an association between a seed and a non-existent seed.
How does it work?
Role.seed(:system_administrator, :role => 'system_administrator')
User.seed(:jdurham, :login => 'jdurham', :roles => [Role.seed(:system_administrator])
if you like blocks, we’ve also got those covered:
Role.seed(:system_administrator) do |role|
role.role = 'system_administrator'endUser.seed(:jdurham) do |user|
user.login = 'jdurham'user.roles = [Role.seed(:system_administrator)]
endThis will create a Role seed, named “system_administrator”, which we will reused in other seeds. That way, when looking at another seed, it’s very obvious what associated data it has.
Overplanting not allowed
Later on, if I decide I want to create a new seed and I do:
Role.seed(:system_administrator, :role => 'admin')
This will raise an exception, because there will be an ambiguity issue. I’m trying to create another seed named system_administrator.
Trying to get a seed that never existed
User.seed(:normal_user, :roles => [Role.seed(:user)])
This will raise an exception because it doesn’t make sense to try to associate a user with a seed that doesn’t exist.
Great, I’ve got seed data. Now, how do I load it?
Seed comes with a rake task that extends the built-in rake db:seed functionality. In your Rakefile add:
require 'seed/task'Now, create a db/seeds directory and add a file; for example, development.rb to that directory. Once you do, you’ll automatically have a rake task that can be invoked as follows:
rake db:seed:development
Hopefully you find Seed useful. We’ve been using it in production for a little while and it’s been working well.