Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix date parsing with complex types #3614

Merged
merged 1 commit into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 3 additions & 9 deletions app/parsers/date_hash_parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ class DateHashParser
def initialize(date_hash)
@date_hash = date_hash
.slice(:day, :month, :year)
.compact_blank
.transform_values(&:to_i)
.transform_values { |value| Integer(value, exception: false) }
.select { |_, value| value&.positive? }
end

def parse
return if date_hash.empty? || any_non_positive_values? || day_without_month?
return if date_hash.empty? || day_without_month?

Date.new(year, month, day)
rescue Date::Error
Expand All @@ -40,12 +40,6 @@ def day_without_month?
date_hash.key?(:day) && !date_hash.key?(:month)
end

def any_non_positive_values?
# If the user enters a zero or negative value, or a string that `#to_i` converts to zero, we
# consider the whole date invalid
!date_hash.values.all?(&:positive?)
end

def day
date_hash.fetch(:day, 1)
end
Expand Down
18 changes: 12 additions & 6 deletions spec/parsers/date_hash_parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,18 @@

it { is_expected.to eq Date.new(2024, 12, 1) }
end

context "with hash with a complex type value" do
let(:date_hash) { { day: [1], month: 12, year: 2024 } }

it { is_expected.to eq Date.new(2024, 12, 1) }
end

context "with hash with any non-numeric values" do
let(:date_hash) { { day: 13, month: 12, year: "baz" } }

it { is_expected.to eq Date.new(2024, 12, 13) }
end
end

describe "invalid input" do
Expand Down Expand Up @@ -99,12 +111,6 @@
it { is_expected.to be_nil }
end

context "with hash with any non-numeric values (even if others are good)" do
let(:date_hash) { { day: 13, month: 12, year: "baz" } }

it { is_expected.to be_nil }
end

context "with hash with non-numeric year only" do
let(:date_hash) { { year: "baz" } }

Expand Down
Loading