Jeremy Durham

Ruby, Rails, and everything in between.

  • BlogThoughts
  • AboutAbout the Author
  • ContactGet in touch

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'
end
User.seed(:jdurham) do |user|
  user.login = 'jdurham'
  user.roles = [Role.seed(:system_administrator)]
end

This 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.

5 Comments

Posted Under Programming

  • Posts
  • Twitter
  • Flickr
 

There is no Holy ...

Technology

 

Google and Apple:...

Technology

 

Setting up Git an...

Technology

@mariusrugan awesome, glad I was able to be of some help

follow me on
twitter

125942640_a3dcc3f951_s125942637_c4524c7c88_s125942628_a682f8a639_s122144184_5f2dd86929_s122144182_1b01ded312_s122144181_893a82f1d3_s122144179_70465b00ff_s122102402_21e6174af6_s122102401_f6d9ebff55_s

Categories

  • Technology
  • Programming
  • Family
  • Travel

This site is using the Handgloves WordPress Theme
Designed & Developed by George Wiscombe

Subscribe via RSS