-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
🔧🏷 Add type coercion for config attributes
This is implemented as another module included under the other two, still based on overriding `attr_accessor`. Types are only enforced by the attr_writer methods. Fortunately, rdoc isn't confused by keyword arguments to `attr_accessor`, so the type can be added to that. Currently, only `:boolean` and `Integer` are supported, but it should be easy to add more.
- Loading branch information
Showing
3 changed files
with
77 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# frozen_string_literal: true | ||
|
||
module Net | ||
class IMAP | ||
class Config | ||
# Adds a +type+ keyword parameter to +attr_accessor+, which enforces | ||
# config attributes have valid types, for example: boolean, numeric, | ||
# enumeration, non-nullable, etc. | ||
module AttrTypeCoercion | ||
# :stopdoc: internal APIs only | ||
|
||
module Macros # :nodoc: internal API | ||
def attr_accessor(attr, type: nil) | ||
super(attr) | ||
AttrTypeCoercion.attr_accessor(attr, type: type) | ||
end | ||
end | ||
private_constant :Macros | ||
|
||
def self.included(mod) | ||
mod.extend Macros | ||
end | ||
private_class_method :included | ||
|
||
def self.attr_accessor(attr, type: nil) | ||
return unless type | ||
if :boolean == type then boolean attr | ||
elsif Integer == type then integer attr | ||
else raise ArgumentError, "unknown type coercion %p" % [type] | ||
end | ||
end | ||
|
||
def self.boolean(attr) | ||
define_method :"#{attr}=" do |val| super !!val end | ||
define_method :"#{attr}?" do send attr end | ||
end | ||
|
||
def self.integer(attr) | ||
define_method :"#{attr}=" do |val| super Integer val end | ||
end | ||
|
||
end | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters