Centralize environmentally dependent config in ENV files

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the architecture category.

Last Updated: 2021-05-15

I had the following intitializer for geocoder:

require_relative './redis'

Geocoder.configure(
  cache: Redis.current, # cache object (must respond to #[], #[]=, and #keys)
)

Unfortunately, the use of Redis as the cache DB was hard-coded here so my seeding environment - which did not and should not include redis - failed to boot.

The fix was to understand that the Rails.application.configure block in the environment-specific files (e.g. development.rb or production.rb or in this weird case: seeds.rb) runs BEFORE any files in the initializers folder, therefore any cache store I configure there would be available elsewhere:

# env/seeds.rb
Rails.application.configure do
  config.cache_store = :memory_store, { size: 64.megabytes }
end

This enables code that references the general cache store (rather than the specific redis one)

# initializers/geocoder.rb
Geocoder.configure(
  cache: Rails.cache
)

The beauty here is that decisions as to dependencies trickle down in one direction: from the env file.

(If environmentally dependent configuration is needed in the ENV file, I should use a yaml file to store that info.)