Skip to content

Commit

Permalink
🔧 Add Config#load_defaults
Browse files Browse the repository at this point in the history
  • Loading branch information
nevans committed Jun 22, 2024
1 parent be8d5cd commit 200b51d
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/net/imap/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,12 @@ class IMAP
# Net::IMAP.debug = true
# client.config.debug? # => true
#
# Use #load_defaults to globally behave like a specific version:
# client = Net::IMAP.new(hostname)
# client.config.sasl_ir # => true
# Net::IMAP.config.load_defaults 0.3
# client.config.sasl_ir # => false
#
# === Named defaults
# In addition to +x.y+ version numbers, the following aliases are supported:
#
Expand Down Expand Up @@ -270,6 +276,20 @@ def with(**attrs)
block_given? ? yield(copy) : copy
end

# :call-seq: load_defaults(version) -> self
#
# Resets the current config to behave like the versioned default
# configuration for +version+.
#
# See Config@Versioned+defaults and Config@Named+defaults.
def load_defaults(version)
[Numeric, Symbol, String].any? { _1 === version } or
raise ArgumentError, "expected number or symbol, got %p" % [version]
config = Config[version]
defaults = config.to_h.reject {|k,v| DEFAULT_TO_INHERIT.include?(k) }
update(**defaults)
end

# :call-seq: to_h -> hash
#
# Returns all config attributes in a hash.
Expand Down
23 changes: 23 additions & 0 deletions test/net/imap/test_config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -332,4 +332,27 @@ class ConfigTest < Test::Unit::TestCase
assert_equal [11, 5, true], vals
end

test "#load_defaults" do
config = Config.global.load_defaults 0.3
assert_same Config.global, config
assert_same true, config.inherited?(:debug)
assert_same false, config.inherited?(:sasl_ir)
assert_same false, config.sasl_ir
# does not _reset_ default
config.debug = true
Config.global.load_defaults 0.3
assert_same false, config.inherited?(:debug)
assert_same true, config.debug?
# does not change parent
child = Config.global.new
grandchild = child.new
greatgrandchild = grandchild.new
child.load_defaults :current
grandchild.load_defaults :next
greatgrandchild.load_defaults :future
assert_same Config.global, child.parent
assert_same child, grandchild.parent
assert_same grandchild, greatgrandchild.parent
end

end

0 comments on commit 200b51d

Please sign in to comment.