Benry-Config
($Release: 0.2.0 $)
What's this?
Utility class to support configuration.
Features:
- Easy to define configuration for environments (production, development, ...).
- Raises error when configuration name is wrong (typo).
- Represents secret configurations which should be set by environment var or in secret file.
Links:
- Document: https://kwatch.github.io/benry-ruby/benry-config.html
- GitHub: https://github.com/kwatch/benry-ruby/tree/main/benry-config
- Changes: https://github.com/kwatch/benry-ruby/tree/main/benry-config/CHANGES.md
Table of Contents
Example
File: config/app.rb
require 'benry/config'
class AppConfigBase < Benry::Config
## add names and values
add :db_host , "localhost"
add :db_user , "user1"
add :db_pass , ABSTRACT # should be set value in subclass
add :session_cookie , "sess"
add :session_secret , SECRET
## or:
#add :db_pass , ABSTRACT['DB_PASS'] # get value from ENV
#add :session_secret , SECRET['SESS_SECRET'] # get secret value from ENV
end
File: config/app_dev.rb (for development environment)
require_relative './app'
## for development environment
class AppConfig < AppConfigBase
## set (= override) existing values
set :db_pass , "pass1" # set ABSTRACT value
end
File: config/app_prod.rb (for production environment)
require_relative './app'
## for production environment
class AppConfig < AppConfigBase
## set (= override) existing values
set :db_host , "db-master" # override existing value
set :db_pass , "passXXX" # set ABSTRACT value
## error because `:db_name` is not defined in paremnt class.
set :db_name , "prod1" #=> Benry::ConfigError (not defined)
end
File: config/app.secret (should be ignored by .gitignore
)
## this file should be ignored by '.gitignore', and
## file permission should be `600`.
AppConfig.class_eval do
set :session_secret , "YRjCIAiPlCBvwLUq5mnZ" # set SECRET value
end
File: main.rb
## load config files
app_env = ENV['APP_ENV'] or raise "$APP_ENV required."
require "./config/app.rb" # define AppConfigBase class
require "./config/app_#{app_env}.rb" # define AppConfig class
load "./config/app.secret" # modify AppConfig class
## or:
#load "./config/app.#{app_env}.secret"
## create a config object
$config = AppConfig.new.freeze
#
p $config.db_user #=> "user1"
p $config.db_pass #=> "pass1"
p $config. #=> "sess"
p $config.session_secret #=> "YRjCIAiPlCBvwLUq5mnZ"
#
p $config.defined?(:db_user) #=> true
p $config.defined?(:db_pass) #=> true
p $config.defined?(:db_name) #=> false
#
p $config.get_all(:db_) #=> {:host=>"localhost", :user=>"user1", :pass=>"pass1"}
p $config.get_all(:session_) #=> {:cookie=>"sess", :secret=>"YRjCIAiPlCBvwLUq5mnZ"}
#
$config.each {|k, v| puts "#{k}=#{v.inspect}" } # hide secret values as "(secret)"
$config.each! {|k, v| puts "#{k}=#{v.inspect}" } # not hide secret values
Copyright and License
- $Copyright: copyright(c) 2016 [email protected] $
- $License: MIT License $