Skip to content

Commit

Permalink
feat: added strong integer (#157)
Browse files Browse the repository at this point in the history
* feat: Added strong integer type

* change test

* Update README.md

---------

Co-authored-by: Vladimir Dementyev <dementiev.vm@gmail.com>
  • Loading branch information
Alex Zavgorodnev and palkan authored Feb 12, 2025
1 parent c6ad3eb commit 7d896e8
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -714,7 +714,7 @@ CoolConfig.new.port == "443" #=> true

**IMPORTANT**: Values provided explicitly (via attribute writers) are not coerced. Coercion is only happening during the load phase.

The following types are supported out-of-the-box: `:string`, `:integer`, `:float`, `:date`, `:datetime`, `:uri`, `:boolean`.
The following types are supported out-of-the-box: `:string`, `:integer`, `:integer!` (strict integer), `:float`, `:date`, `:datetime`, `:uri`, `:boolean`.

You can use custom deserializers by passing a callable object instead of a type name:

Expand Down
4 changes: 4 additions & 0 deletions lib/anyway/type_casting.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ def dup
obj.accept(:boolean) do
_1.to_s.match?(/\A(true|t|yes|y|1)\z/i)
end

obj.accept(:integer!) do
Integer(_1)
end
end

unless "".respond_to?(:safe_constantize)
Expand Down
2 changes: 2 additions & 0 deletions spec/type_casting_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
specify "default types" do
expect(casting.deserialize("12", :string)).to eq("12")
expect(casting.deserialize("12.3", :integer)).to eq(12)
expect(casting.deserialize("12", :integer!)).to eq(12)
expect { casting.deserialize("f", :integer!) }.to raise_error(ArgumentError, /invalid value for Integer()/)
expect(casting.deserialize("12.3", :float)).to eq(12.3)
expect(casting.deserialize("2020-08-30 17:01:03", :date)).to eq(Date.parse("2020-08-30"))
expect(casting.deserialize(Time.local(2020, 8, 30, 11, 44, 22), :date)).to eq(Date.parse("2020-08-30"))
Expand Down

0 comments on commit 7d896e8

Please sign in to comment.