Skip to content

Commit

Permalink
Detect and cast values with int & float defaults
Browse files Browse the repository at this point in the history
  • Loading branch information
meatballhat committed Apr 11, 2017
1 parent 64d1115 commit 1aa6fa7
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/hashr/env.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ def cast(value, default, keys)
value.respond_to?(:split) ? value.split(',') : Array(value)
when true, false
not FALSE.include?(value)
when Integer then Integer(value)
when Float then Float(value)
else
value
end
Expand Down
43 changes: 42 additions & 1 deletion spec/hashr/env_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
define string: 'string',
hash: { key: 'value' },
array: ['foo', 'bar'],
bool: false
bool: false,
int: 4,
float: 11.1
end
end

Expand Down Expand Up @@ -55,6 +57,45 @@
expect(klass.new.array).to eq([])
end
end

describe 'to an int' do
it 'int given' do
ENV['HASHR_INT'] = '1'
expect(klass.new.int).to eq(1)
end

it 'errors for an empty string' do
ENV['HASHR_INT'] = ''
expect { klass.new.int }.to raise_error(ArgumentError)
end

it 'errors for a non-int' do
ENV['HASHR_INT'] = 'a'
expect { klass.new.int }.to raise_error(ArgumentError)
end
end

describe 'to a float' do
it 'float given' do
ENV['HASHR_FLOAT'] = '2.3'
expect(klass.new.float).to eq(2.3)
end

it 'int given' do
ENV['HASHR_FLOAT'] = '4'
expect(klass.new.float).to eq(4.0)
end

it 'errors for an empty string' do
ENV['HASHR_FLOAT'] = ''
expect { klass.new.float }.to raise_error(ArgumentError)
end

it 'errors for a non-float' do
ENV['HASHR_FLOAT'] = 'a'
expect { klass.new.float }.to raise_error(ArgumentError)
end
end
end

it 'data takes precedence over an env var' do
Expand Down

0 comments on commit 1aa6fa7

Please sign in to comment.