File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -165,6 +165,24 @@ def update(**attrs)
165165 self
166166 end
167167
168+ # :call-seq:
169+ # with(**attrs) -> config
170+ # with(**attrs) {|config| } -> result
171+ #
172+ # Without a block, returns a new config which inherits from self. With a
173+ # block, yields the new config and returns the block's result.
174+ #
175+ # If no keyword arguments are given, an ArgumentError will be raised.
176+ #
177+ # If +self+ is frozen, the copy will also be frozen.
178+ def with ( **attrs )
179+ attrs . empty? and
180+ raise ArgumentError , "expected keyword arguments, none given"
181+ copy = new ( **attrs )
182+ copy . freeze if frozen?
183+ block_given? ? yield ( copy ) : copy
184+ end
185+
168186 # :call-seq: to_h -> hash
169187 #
170188 # Returns all config attributes in a hash.
Original file line number Diff line number Diff line change @@ -253,4 +253,29 @@ class ConfigTest < Test::Unit::TestCase
253253 assert_same false , config . sasl_ir? # unchanged
254254 end
255255
256+ test "#with" do
257+ orig = Config . new ( open_timeout : 123 , sasl_ir : false )
258+ assert_raise ( ArgumentError ) do
259+ orig . with
260+ end
261+ copy = orig . with ( open_timeout : 456 , idle_response_timeout : 789 )
262+ refute copy . frozen?
263+ assert_same orig , copy . parent
264+ assert_equal 123 , orig . open_timeout # unchanged
265+ assert_equal 456 , copy . open_timeout
266+ assert_equal 789 , copy . idle_response_timeout
267+ vals = nil
268+ result = orig . with ( open_timeout : 99 , idle_response_timeout : 88 ) do |c |
269+ vals = [ c . open_timeout , c . idle_response_timeout , c . frozen? ]
270+ :result
271+ end
272+ assert_equal :result , result
273+ assert_equal [ 99 , 88 , false ] , vals
274+ orig . freeze
275+ result = orig . with ( open_timeout : 11 ) do |c |
276+ vals = [ c . open_timeout , c . idle_response_timeout , c . frozen? ]
277+ end
278+ assert_equal [ 11 , 5 , true ] , vals
279+ end
280+
256281end
You can’t perform that action at this time.
0 commit comments