Skip to content

Commit

Permalink
🔧 Add Config#with(**attrs) to make child configs
Browse files Browse the repository at this point in the history
  • Loading branch information
nevans committed Jun 22, 2024
1 parent 381c885 commit b72c221
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/net/imap/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,24 @@ def update(**attrs)
self
end

# :call-seq:
# with(**attrs) -> config
# with(**attrs) {|config| } -> result
#
# Without a block, returns a new config which inherits from self. With a
# block, yields the new config and returns the block's result.
#
# If no keyword arguments are given, an ArgumentError will be raised.
#
# If +self+ is frozen, the copy will also be frozen.
def with(**attrs)
attrs.empty? and
raise ArgumentError, "expected keyword arguments, none given"
copy = new(**attrs)
copy.freeze if frozen?
block_given? ? yield(copy) : copy
end

# :call-seq: to_h -> hash
#
# Returns all config attributes in a hash.
Expand Down
25 changes: 25 additions & 0 deletions test/net/imap/test_config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -253,4 +253,29 @@ class ConfigTest < Test::Unit::TestCase
assert_same false, config.sasl_ir? # unchanged
end

test "#with" do
orig = Config.new(open_timeout: 123, sasl_ir: false)
assert_raise(ArgumentError) do
orig.with
end
copy = orig.with(open_timeout: 456, idle_response_timeout: 789)
refute copy.frozen?
assert_same orig, copy.parent
assert_equal 123, orig.open_timeout # unchanged
assert_equal 456, copy.open_timeout
assert_equal 789, copy.idle_response_timeout
vals = nil
result = orig.with(open_timeout: 99, idle_response_timeout: 88) do |c|
vals = [c.open_timeout, c.idle_response_timeout, c.frozen?]
:result
end
assert_equal :result, result
assert_equal [99, 88, false], vals
orig.freeze
result = orig.with(open_timeout: 11) do |c|
vals = [c.open_timeout, c.idle_response_timeout, c.frozen?]
end
assert_equal [11, 5, true], vals
end

end

0 comments on commit b72c221

Please sign in to comment.