A set of tools to tidy up rails seeds.rb files.
Dibber has two compoments:
Seeder is designed to simplify the process of pulling attributes from YAML files, and populating ActiveRecord objects with those attributes.
ProcessLog provides Seeder with a simple before and after reporting tool.
Add this to your Gemfile:
You have a rails app with a Thing model, and you want to seed it with some things. Thing instances have the attributes 'name', 'colour', 'size'. You have a YAML file 'db/seeds/things.yml' that looks like this:
foo: colour: red size: large bar: colour: blue size: small
Add this to your 'db/seeds.rb'
Seeder = Dibber::Seeder Seeder.seed :thing puts Seeder.report
Then run 'rake db:seed'
Seeder will create two new things.
You'll then be able to do this:
thing = Thing.find_by(name: 'foo') thing.colour ---> 'red'
Dibber can be used outside of Rails, but in this case you will need to specify the location of the seed files.
Seeder.seeds_path = "some/path/to/seeds"
You can also use this technique in Rails if you want to put your seed files in a folder other than 'db/seeds'
Seeder.report outputs a report detailing start and end time, and a log of how the number of things has changed
Overwriting existing entries
Seeder#build will not overwrite existing data unless directed to do so.
thing.update_attribute(:colour, 'black') Seeder.seed :thing thing.reload.colour ----> 'black' Seeder.seed(:thing, overwrite: true) thing.reload.colour ----> 'red'
Using alternative class and field name mappings
Seeder.seed calls Seeder#build to build the objects defined in the seed files. You can call the build method directly if your seed file names do not match the class name:
Take a look at test/examples/seeds.rb for some more usage examples.
If you clone this app, you can run this example at the project root:
There is also an example of process log usage: