Skip to content

Commit

Permalink
Change date conversion to work with date objects
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Dec 28, 2022
1 parent 33b874c commit 045651b
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* Change permit setting to work with parameters converted to an array or a hash
* Change formatting of a hash value in parameter validation error message
* Change array and hash conversions to work with non-string values
* Change date conversion to work with date objects

### Fixed
* Fix argument check against permitted values to allow nil value when optional
Expand Down
4 changes: 3 additions & 1 deletion lib/tty/option/conversions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ module Conversions
end

convert :date do |val|
require "date" unless defined?(::Date)
next val if val.is_a?(::Date)

begin
require "date" unless defined?(::Date)
::Date.parse(val)
rescue ArgumentError, TypeError
Const::Undefined
Expand Down
5 changes: 3 additions & 2 deletions spec/unit/conversions_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,15 @@
{
"28/03/2020" => Date.parse("28/03/2020"),
"March 28th 2020" => Date.parse("28/03/2020"),
"Sun, March 28th, 2020" => Date.parse("28/03/2020")
"Sun, March 28th, 2020" => Date.parse("28/03/2020"),
Date.parse("28/03/2020") => Date.parse("28/03/2020")
}.each do |input, obj|
it "converts #{input.inspect} to #{obj.inspect}" do
expect(described_class[:date].(input)).to eq(obj)
end
end

it "fails to convert" do
it "fails to convert a string" do
expect(described_class[:date].("invalid")).to eq(undefined)
end

Expand Down
15 changes: 15 additions & 0 deletions spec/unit/parse_spec.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require "date"

RSpec.describe TTY::Option do
context "argument" do
it "doesn't allow to register same name parameter" do
Expand Down Expand Up @@ -711,6 +713,19 @@
expect(cmd.params[:foo]).to eq({a: %w[1 3], b: "2"})
expect(cmd.params[:bar]).to eq({c: 1, d: 2})
end

it "converts an option value to a date" do
cmd = new_command do
option :foo do
long "--foo VAL"
convert :date
end
end

cmd.parse(%w[--foo 28/12/2022])

expect(cmd.params[:foo]).to eq(Date.new(2022, 12, 28))
end
end

context "permit" do
Expand Down

0 comments on commit 045651b

Please sign in to comment.