Commit Redux

A software development blog in commit-sized retrospectives

New rake task to populate seeds.rb

Saturday May 10 2025 • 10:52 PM

[main 8956963] New rake task to populate seeds.rb
   3 files changed, 242 insertions(+)
   create mode 100644 db/seeds.rb
   create mode 100644 lib/tasks/export_seeds.rake

Every post written in Commit Redux so far has been stored in the development sqlite database. While this is okay for local development, yesterday I spent way too much time trying to make new dokku containers connect with persistent storage on the host computer, and even when it did the database was read-only.

On the other hand, deploying with dokku and using postgresql for production makes things infinitely simpler.

Now the challenge is to take all the blog posts I’ve been writing here and populate the production database with them. To do this I’ll be writing a Rake task.

Creating a new task

I’ll follow the Rails directory structure and create the file /lib/tasks/export_seeds.rake.


# lib/tasks/export_seeds.rake
namespace :db do
  desc "Export data from development database to seeds.rb format"
  task export_seeds: :environment do
    File.open("db/seeds.rb", "w") do |file|
      file.puts "# Auto-generated seed data"
      
      Post.find_each do |post|
        file.puts <<~RUBY
          Post.create!(
            title: #{post.title.inspect},
            content: #{post.content.inspect},
            created_at: #{post.created_at.utc.iso8601.inspect},
            updated_at: #{post.updated_at.utc.iso8601.inspect}
          )
        RUBY
      end

    end
    puts "✅ Seed data written to db/seeds.rb"
  end
end

Update config/environment.rb

Next I update my environment file to import the new rake task.


require 'sinatra/activerecord/rake'
require './config/environment'
import './lib/tasks/export_seeds.rake'

The seeds.rb file

With elements in this format in the seeds.rb file I can push this file to production and run dokku run commit-redux rake db:seed to populate the blog with the words you’re reading right now 😎


# Auto-generated seed data
Post.create!(
  title: "Hello, world!",
  content: "This is the very first post in my new Sinatra app for blogging :)",
  created_at: "2025-05-07T07:47:38Z",
  updated_at: "2025-05-07T07:47:38Z"
)

And now this blog has all the posts I wrote during development this past week, and new posts can continue being written directly on the site here.

Update: I inadvertently created a bug by also dumping the ID data. Totally unnecessary, so I removed that column from the export task.