Skip to content

Commit 4a96fa2

Browse files
committed
🔧 Check type for config.responses_without_block
An `enum` type was added to Config::AttrTypeCoercion, to be used by other future config options.
1 parent fa5ba2a commit 4a96fa2

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

lib/net/imap/config.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,9 @@ def self.[](config) # :nodoc: unfinished API
9090
# | v0.4.13 | +:silence_deprecation_warning+ |
9191
# | v0.5 | +:warn+ |
9292
# | _eventually_ | +:raise+ |
93-
attr_accessor :responses_without_block
93+
attr_accessor :responses_without_block, type: [
94+
:silence_deprecation_warning, :warn, :raise,
95+
]
9496

9597
# Creates a new config object and initialize its attribute with +attrs+.
9698
#

lib/net/imap/config/attr_type_coercion.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ def self.attr_accessor(attr, type: nil)
2626
return unless type
2727
if :boolean == type then boolean attr
2828
elsif Integer == type then integer attr
29+
elsif Array === type then enum attr, type
2930
else raise ArgumentError, "unknown type coercion %p" % [type]
3031
end
3132
end
@@ -39,6 +40,17 @@ def self.integer(attr)
3940
define_method :"#{attr}=" do |val| super Integer val end
4041
end
4142

43+
def self.enum(attr, enum)
44+
enum = enum.dup.freeze
45+
expected = -"one of #{enum.map(&:inspect).join(", ")}"
46+
define_method :"#{attr}=" do |val|
47+
unless enum.include?(val)
48+
raise ArgumentError, "expected %s, got %p" % [expected, val]
49+
end
50+
super val
51+
end
52+
end
53+
4254
end
4355
end
4456
end

test/net/imap/test_config.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,22 @@ class ConfigTest < Test::Unit::TestCase
5050
assert_equal 333, config.open_timeout
5151
end
5252

53+
test "enum type constraint" do
54+
config = Config.new
55+
config.responses_without_block = :silence_deprecation_warning
56+
assert_equal :silence_deprecation_warning, config.responses_without_block
57+
config.responses_without_block = :warn
58+
assert_equal :warn, config.responses_without_block
59+
config.responses_without_block = :raise
60+
assert_equal :raise, config.responses_without_block
61+
assert_raise(ArgumentError) do config.responses_without_block = false end
62+
assert_equal :raise, config.responses_without_block
63+
assert_raise(ArgumentError) do config.responses_without_block = 12345 end
64+
assert_equal :raise, config.responses_without_block
65+
assert_raise(ArgumentError) do config.responses_without_block = "warn" end
66+
assert_equal :raise, config.responses_without_block
67+
end
68+
5369
test ".default" do
5470
default = Config.default
5571
assert default.equal?(Config.default)

0 commit comments

Comments
 (0)