Skip to content

Commit

Permalink
feat: cast integer values
Browse files Browse the repository at this point in the history
  • Loading branch information
marcosgz committed Oct 7, 2024
1 parent 9c83c59 commit 4438d82
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
18 changes: 11 additions & 7 deletions lib/esse/cli/parser/bool_or_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,20 @@ def parse(input)
private

def may_array(value)
return may_bool(value) unless ARRAY_SEPARATOR.match?(value)
return cast(value) unless ARRAY_SEPARATOR.match?(value)

value.split(ARRAY_SEPARATOR).map { |v| may_bool(v) }
value.split(ARRAY_SEPARATOR).map { |v| cast(v) }
end

def may_bool(value)
return true if TRUTHY.include?(value)
return false if FALSEY.include?(value)

value
def cast(value)
case value
when *TRUTHY then true
when *FALSEY then false
when /\A\d+\z/ then value.to_i
when /\A\d+\.\d+\z/ then value.to_f
else
value
end
end
end
end
Expand Down
12 changes: 10 additions & 2 deletions spec/esse/cli/parser/bool_or_hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@
end

it 'split comma separated values' do
expect(parser.parse('a:1,2,3')).to eq(a: %w[1 2 3])
expect(parser.parse('a:1,2,3 b:4,5,6')).to eq(a: %w[1 2 3], b: %w[4 5 6])
expect(parser.parse('a:c,d,e')).to eq(a: %w[c d e])
expect(parser.parse('a:x,y,z b:p,q,r')).to eq(a: %w[x y z], b: %w[p q r])
expect(parser.parse('a:b,c:d')).to eq(a: %w[b c:d])
end

Expand All @@ -94,6 +94,14 @@
expect(parser.parse('foo:true')).to eq(foo: true)
expect(parser.parse('foo:false')).to eq(foo: false)
end

it 'coerces the value of hash to integer' do
expect(parser.parse('foo:123')).to eq(foo: 123)
end

it 'coerces the value of hash to float' do
expect(parser.parse('foo:123.456')).to eq(foo: 123.456)
end
end
end
end

0 comments on commit 4438d82

Please sign in to comment.