Skip to content

Instantly share code, notes, and snippets.

@pat
Last active November 28, 2023 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pat/336b679079fd9b1e469e8051a5c6edfc to your computer and use it in GitHub Desktop.
Save pat/336b679079fd9b1e469e8051a5c6edfc to your computer and use it in GitHub Desktop.
Dry-driven settings

To ensure it's available for all initialisers, you can require the file within config/application.rb by adding require_relative "settings" as the last line within the Application class definition.

The defined settings will be available via the Settings constant: e.g. Settings.default_host

  • Does not pay attention to Rails.configuration / Rails.application.credentials - it's expecting all secrets as ENV variables.
  • Requires dry-types and dry-system gems.
  • Allows for typed values (even if the above examples are all strings 😅).
  • Allows for optional values and defaults.
  • Inspired by Hanami's approach to such things.
# config/settings.rb
# frozen_string_literal: true
require "dry/system/provider_sources/settings/config"
require "dry/types"
class SettingsSchema < Dry::System::ProviderSources::Settings::Config
include Dry.Types()
setting :bugsnag_api_key, constructor: Strict::String, default: "placeholder"
setting :bugsnag_release_stage, constructor: Strict::String, default: "production"
setting :default_host, constructor: Strict::String, default: "calmcalendar.com"
setting :postmark_api_token, constructor: Strict::String, default: "placeholder"
setting :sidekiq_username, constructor: Strict::String.optional, default: nil
setting :sidekiq_password, constructor: Strict::String.optional, default: nil
def verify!
config._settings.each do |setting|
self[setting.name]
rescue Dry::Types::ConstraintError
raise ArgumentError, "Missing environment variable #{setting.name.upcase}"
end
finalize!
end
end
Settings = SettingsSchema.load(root: Rails.root, env: Rails.env).tap(&:verify!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment