I'm a 37'ish year old web application developer from South Portland, Maine. I love meeting fellow techies, drop me a line if you want to talk shop.
Posted on 09/30/2010 at 12:19 AM
Tonight I discovered a lighthouse ticket by Postmodern. In it, he asks about adding an environment aware feature to the existing ‘rake db:seed’ task, so that he could seed specific environments differently. He even includes a patch.
If you haven’t used rails ‘rake db:seed’ functionality, its quite handy. I use it primarily during the pre-launch phase of development to fill out my app with dummy data, most of which is generated using the ffaker gem. That all works fine for me!
Up until ... the time that my client wants to see progress and I need to deploy my code to a staging server. For that I require an entirely different set of seed data. Try as I might, I just can’t get the client used to my beloved “Lorem ipsum dolor”. So, environment aware seeding is very useful to me.
A neat thing about rake tasks is that when you redeclare a task, it doesnt overwrite the previous one. So, to use postmodern’s patch all you have to do is paste the following code to the bottom of your Rakefile and you’ll reap the full benefits.
namespace :db do
task :seed => :environment do
env_seed_file = File.join(Rails.root, 'db', 'seeds', "#{Rails.env}.rb")
load(env_seed_file) if File.exist?(env_seed_file)
end
end
Now you can do stuff like this! (the env specific file is loaded after the regular seeds file)
db
├── seeds
│ ├── development.rb
│ ├── production.rb
│ └── staging.rb
└── seeds.rb
Thanks Postmodern
This was helpful, thanks. One nit: you shouldn’t re-declare the db:seed task in the Rakefile directly, but rather do it in it’s own file under lib/tasks, i.e. lib/tasks/env_db_seed.rake
Cheers.
Helpful post. One more tip:
Rails.root.join ‘db’, ‘seeds’, “#{Rails.env.downcase}.rb”
I put together a little gem to do just this as the feature request has stalled.
Wouldn’t it be easier to just add this to the seeds.rb file and not overriding the task?
```
load(Rails.root.join( ‘db’, ‘seeds’, “#{Rails.env}.rb"))
```
Often times I will release code for free or go that extra distance to help others online. If my skills were useful to you, please consider a small donation. Thank you very much.
@ github.com
@ twitter.com
@ calendaraboutnothing
Foundation's Edge, RJones Family, We're Not.com (only for staging), Ailee Jones (same as rjones for now)
Aaron, Barnaby, Brian, Chris, Dirk, Frank, Four, Justin, Matt, Mike, Monty, Paul, Sean, Travis
I can usually be found lounging on irc.freenode.net while I work, on the following channels: #fauna, #github, #hello-heroku, #jquery, #passenger, #ruby, #rubyonrails, #slicehost, #sproutcore, #textmate, #werenot.
Amazing.....rails is smooth