Skip to content

Commit

Permalink
Merge pull request #358 from Azdaroth/handle-typecasting-when-using-s…
Browse files Browse the repository at this point in the history
…et-method

handle type-casting for config, even when explicitly setting values using .set method
  • Loading branch information
michaelklishin authored Apr 3, 2021
2 parents 9a39da1 + a14d0ec commit 0cffda5
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 9 deletions.
23 changes: 14 additions & 9 deletions lib/hutch/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -196,14 +196,7 @@ def self.env_based_config
env_keys_configured.each_with_object({}) {|attr, result|
value = ENV[key_for(attr)]

case
when is_bool(attr) || value == 'false'
result[attr] = to_bool(value)
when is_num(attr)
result[attr] = value.to_i
else
result[attr] = value
end
result[attr] = type_cast(attr, value)
}
end

Expand Down Expand Up @@ -238,7 +231,7 @@ def self.is_num(attr)

def self.set(attr, value)
check_attr(attr.to_sym)
user_config[attr.to_sym] = value
user_config[attr.to_sym] = type_cast(attr, value)
end

class << self
Expand Down Expand Up @@ -275,6 +268,18 @@ def self.convert_value(attr, value)
end
end

def self.type_cast(attr, value)
case
when is_bool(attr) || value == 'false'
to_bool(value)
when is_num(attr)
value.to_i
else
value
end
end
private_class_method :type_cast

def self.define_methods
@config.keys.each do |key|
define_singleton_method(key) do
Expand Down
38 changes: 38 additions & 0 deletions spec/hutch/config_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,44 @@
context 'sets value in user config hash' do
it { is_expected.to eq(new_value) }
end

context 'type casting' do
context 'number attributes' do
before { Hutch::Config.set(:heartbeat, new_value) }
subject(:value) { Hutch::Config.user_config[:heartbeat] }

let(:new_value) { "0" }


specify 'casts values to integers' do
expect(value).to eq 0
end
end
end

context 'boolean attributes' do
before { Hutch::Config.set(:autoload_rails, new_value) }
subject(:value) { Hutch::Config.user_config[:autoload_rails] }

let(:new_value) { "t" }


specify 'casts values to booleans' do
expect(value).to eq true
end
end

context 'string attributes' do
before { Hutch::Config.set(:mq_exchange_type, new_value) }
subject(:value) { Hutch::Config.user_config[:mq_exchange_type] }

let(:new_value) { 1 }


specify 'does not perform any typecasting' do
expect(value).to eq new_value
end
end
end

context 'for invalid attributes' do
Expand Down

0 comments on commit 0cffda5

Please sign in to comment.