Skip to content

Commit

Permalink
fix: type casting for ints and dates
Browse files Browse the repository at this point in the history
  • Loading branch information
isqad committed Jan 31, 2020
1 parent 974e840 commit d992baf
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
12 changes: 11 additions & 1 deletion lib/treasury/hash_serializer.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
module Treasury
module HashSerializer
INT_PATTERN = /\A\d+\Z/.freeze
DATE_PATTERN = /\A[1,2][0-9]{3}-(?:0[1-9]|1[0-2])-(?:[0-2][1-9]|3[0-1])\Z/.freeze

def deserialize(hash_string)
return Hash.new if hash_string.blank?

hash_data = hash_string
.split(',')
.map do |item|
key, value = item.split(':')
[key, value.to_i]

if value =~ INT_PATTERN
[key, value.to_i]
elsif value =~ DATE_PATTERN
[key, value.to_date]
else
[key, value]
end
end

Hash[hash_data]
Expand Down
30 changes: 25 additions & 5 deletions spec/lib/treasury/fields/hash_operations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,35 @@

describe "#value_as_hash" do
let(:value_as_hash) { hash_field_class.value_as_hash(object: 123, field: :count) }
let(:value) { '10:100,20:200' }

before do
allow(hash_field_class).to receive(:value).and_return(value)
end

it do
expect(hash_field_class).to receive(:init_accessor).with(object: 123, field: :count)
expect(value_as_hash).to eq('10' => 100, '20' => 200)
context 'when values is ints' do
let(:value) { '10:100,20:200' }

it do
expect(hash_field_class).to receive(:init_accessor).with(object: 123, field: :count)
expect(value_as_hash).to eq('10' => 100, '20' => 200)
end
end

context 'when values is dates' do
let(:value) { '10:2019-12-31,20:1999-10-01' }

it do
expect(hash_field_class).to receive(:init_accessor).with(object: 123, field: :count)
expect(value_as_hash).to eq('10' => Date.parse('2019-12-31'), '20' => Date.parse('1999-10-01'))
end
end

context 'when values is strings' do
let(:value) { '10:8888-12-31,20:foobar' }

it do
expect(hash_field_class).to receive(:init_accessor).with(object: 123, field: :count)
expect(value_as_hash).to eq('10' => '8888-12-31', '20' => 'foobar')
end
end
end
end

0 comments on commit d992baf

Please sign in to comment.