Skip to content

Feedback Request: Expose application to seeds #315

@rhyselsmore

Description

@rhyselsmore

Something that has bothered me for a while is the lack of application/constants/environment available during seeds. It is tedious to require manually, and the lack of access to models during my seeds makes me sad.

I did some exploration of using Sequel sharding + some other hacks to try and make the db:seed command support multiple databases (as when seeding locally), however it proved to be a cludge. Fork also seemed pretty terrible. The tl;dr is that we generally need a fresh environment each time the seeds are run.

As such, I have come up with the following:


namespace :db do
  desc "Seed the database with data"
  task :seed do
    if !ENV["DATABASE_URL"]
      sh "rake db:seed:development"
      sh "rake db:seed:testing"
    else
      seed
    end
  end

  namespace :seed do
    task :development do
      seed(env_file: ".env")
    end

    task :testing do
      seed(env_file: ".env.test")
    end
  end

  def seed(env_file: nil)
    require 'bundler'

    if env_file
      Bundler.require(:default, :test)
      require 'dotenv'
      Dotenv.load '.env'
    else
      Bundler.require
    end

    load "lib/initializer.rb"
    load "db/seeds.rb"
  end
end

It works like this:

  • If DATABASE_URL is set, it simply loads the application, and then runs the seeds.
  • If DATABASE_URL is not set, it assumes that we are local, and shells out 2 times, running the seeds in each environment.

This allows us to keep rake db:seed, but also exposes the application to the seeds.rb file.

Would you be interested in this being formalized into a PR, and being included in Pliny?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions