Skip to content

Commit

Permalink
🔧 Check type for config.responses_without_block
Browse files Browse the repository at this point in the history
An `enum` type was added to Config::AttrTypeCoercion, to be used by
other future config options.
  • Loading branch information
nevans committed Jun 15, 2024
1 parent 3c0be7d commit ca8e26d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/net/imap/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,9 @@ def self.[](config) # :nodoc: unfinished API
# | v0.4.13 | +:silence_deprecation_warning+ |
# | v0.5 | +:warn+ |
# | _eventually_ | +:raise+ |
attr_accessor :responses_without_block
attr_accessor :responses_without_block, type: [
:silence_deprecation_warning, :warn, :raise,
]

# Creates a new config object and initialize its attribute with +attrs+.
#
Expand Down
12 changes: 12 additions & 0 deletions lib/net/imap/config/attr_type_coercion.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def self.attr_accessor(attr, type: nil)
return unless type
if :boolean == type then boolean attr
elsif Integer == type then integer attr
elsif Array === type then enum attr, type
else raise ArgumentError, "unknown type coercion %p" % [type]
end
end
Expand All @@ -39,6 +40,17 @@ def self.integer(attr)
define_method :"#{attr}=" do |val| super Integer val end
end

def self.enum(attr, enum)
enum = enum.dup.freeze
expected = -"one of #{enum.map(&:inspect).join(", ")}"
define_method :"#{attr}=" do |val|
unless enum.include?(val)
raise ArgumentError, "expected %s, got %p" % [expected, val]
end
super val
end
end

end
end
end
Expand Down
16 changes: 16 additions & 0 deletions test/net/imap/test_config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,22 @@ class ConfigTest < Test::Unit::TestCase
assert_equal 333, config.open_timeout
end

test "enum type constraint" do
config = Config.new
config.responses_without_block = :silence_deprecation_warning
assert_equal :silence_deprecation_warning, config.responses_without_block
config.responses_without_block = :warn
assert_equal :warn, config.responses_without_block
config.responses_without_block = :raise
assert_equal :raise, config.responses_without_block
assert_raise(ArgumentError) do config.responses_without_block = false end
assert_equal :raise, config.responses_without_block
assert_raise(ArgumentError) do config.responses_without_block = 12345 end
assert_equal :raise, config.responses_without_block
assert_raise(ArgumentError) do config.responses_without_block = "warn" end
assert_equal :raise, config.responses_without_block
end

test ".default" do
default = Config.default
assert default.equal?(Config.default)
Expand Down

0 comments on commit ca8e26d

Please sign in to comment.