The other day I had a request from my IT guy. He asked: “Hey, can you make rails not connect to the database when running assets precompile?” I said sure…
So why would we need to run a precompile without db connection? Well, for one thing, we are deploying to gcloud. For our current set up we run assets precompile on each container before it launches. I am not sure of the specifics but that’s how it is set up. so to make things faster it would be nice if we didn’t need to connect to a db.
In rails 3 you could disable loading rails and thus skipping the database connection by adding this to your application.rb
config.assets.initialize_on_precompile = false
This was removed in rails 4 without any official alternative. Thankfully there are two workarounds that we combined to achieve our goal. We took pointers from these two articles:
- Errors when precompiling assets in Rails 4.0
While the last article details an acceptable solution, it does required us to have logic on our database yaml. While that’s common practice I rather avoid such things.
so for our solution we did two thing:
- Added this gem to the Gemfile
- Modified our assets precompile command to look like this:
bundle exec rake RAILS_ENV=staging DATABASE_URL=nulldb://user:firstname.lastname@example.org/dbname assets:precompile