Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feedback Request: Expose application to seeds #315

Open
rhyselsmore opened this issue Aug 25, 2017 · 0 comments
Open

Feedback Request: Expose application to seeds #315

rhyselsmore opened this issue Aug 25, 2017 · 0 comments

Comments

@rhyselsmore
Copy link

rhyselsmore commented Aug 25, 2017

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant