From 4438d82695ff4ea837b75f973312f275f08288b0 Mon Sep 17 00:00:00 2001 From: "Marcos G. Zimmermann" Date: Mon, 7 Oct 2024 08:34:42 -0300 Subject: [PATCH] feat: cast integer values --- lib/esse/cli/parser/bool_or_hash.rb | 18 +++++++++++------- spec/esse/cli/parser/bool_or_hash_spec.rb | 12 ++++++++++-- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/lib/esse/cli/parser/bool_or_hash.rb b/lib/esse/cli/parser/bool_or_hash.rb index 265de09..7a0aaa5 100644 --- a/lib/esse/cli/parser/bool_or_hash.rb +++ b/lib/esse/cli/parser/bool_or_hash.rb @@ -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 diff --git a/spec/esse/cli/parser/bool_or_hash_spec.rb b/spec/esse/cli/parser/bool_or_hash_spec.rb index 69b8d8e..8f81213 100644 --- a/spec/esse/cli/parser/bool_or_hash_spec.rb +++ b/spec/esse/cli/parser/bool_or_hash_spec.rb @@ -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 @@ -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