interagent / pliny

An opinionated toolkit for writing excellent APIs in Ruby.
MIT License
801 stars 73 forks source link

Feedback Request: Expose application to seeds #315

Open rhyselsmore opened 7 years ago

rhyselsmore commented 7 years ago

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:

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?