diff --git a/README.md b/README.md index fea1309d..9f2db896 100644 --- a/README.md +++ b/README.md @@ -453,7 +453,7 @@ You can customize how environment variables are processed: * `env_converter` (default: `:downcase`) - how to process variables names: * `nil` - no change * `:downcase` - convert to lower case -* `env_parse_values` (default: `true`) - try to parse values to a correct type (`Boolean`, `Integer`, `Float`, `String`) +* `env_parse_values` (default: `true`) - try to parse values to a correct type (`Boolean`, `Integer`, `Float`, `String` & `Symbol`) For instance, given the following environment: @@ -461,6 +461,8 @@ For instance, given the following environment: SETTINGS__SECTION__SERVER_SIZE=1 SETTINGS__SECTION__SERVER=google.com SETTINGS__SECTION__SSL_ENABLED=false +SETTINGS__SECTION__SERVER_TYPE=:remote +SETTINGS__SECTION__SERVER_ACCESS=::ENABLED ``` And the following configuration: @@ -481,6 +483,8 @@ The following settings will be available: Settings.section.server_size # => 1 Settings.section.server # => 'google.com' Settings.section.ssl_enabled # => false +Settings.section.server_type # => :remote +Settings.section.server_access # => '::ENABLED' ``` ### Working with AWS Secrets Manager diff --git a/lib/config/sources/env_source.rb b/lib/config/sources/env_source.rb index df59e35e..c03d6cf1 100644 --- a/lib/config/sources/env_source.rb +++ b/lib/config/sources/env_source.rb @@ -59,15 +59,25 @@ def load # Try to convert string to a correct type def __value(v) - case v - when 'false' - false - when 'true' - true + if %w(true false).include? v + eval(v) + elsif v.strip =~ /^:[^:]/ + convert_str_to_symbol(v) else Integer(v) rescue Float(v) rescue v end end + + # Remove all special characters from a string before converting into a symbol + def convert_str_to_symbol(str) + str. + gsub(/[^a-z0-9\-_]+/i, "-"). + gsub(/-{2,}/, "-"). + gsub(/^-|-$/i, ""). + tr("-", "_"). + downcase. + to_sym + end end end end diff --git a/spec/config_env_spec.rb b/spec/config_env_spec.rb index 65e7da8b..7b160de2 100644 --- a/spec/config_env_spec.rb +++ b/spec/config_env_spec.rb @@ -77,6 +77,16 @@ expect(config.new_var.is_a? Float).to eq(true) end + it 'should recognize strings starting with : as symbols' do + ENV['Settings.new_var'] = ':remote' + expect(config.new_var).to eq(:remote) + end + + it 'should leave strings starting with :: intact' do + ENV['Settings.new_var'] = '::ENABLED' + expect(config.new_var).to eq('::ENABLED') + end + it 'should leave strings intact' do ENV['Settings.new_var'] = 'foobar'