Module: Net::IMAP::Config::AttrTypeCoercion

Included in:
Net::IMAP::Config
Defined in:
lib/net/imap/config/attr_type_coercion.rb

Overview

NOTE: This module is an internal implementation detail, with no guarantee of backward compatibility.

Adds a type keyword parameter to attr_accessor, to enforce that config attributes have valid types, for example: boolean, numeric, enumeration, non-nullable, etc.

Class Method Summary collapse

Class Method Details

.attr_accessor(attr, type: nil) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/net/imap/config/attr_type_coercion.rb', line 29

def self.attr_accessor(attr, type: nil)
  return unless type
  if    :boolean == type then boolean attr
  elsif Integer  == type then integer attr
  elsif Array   === type then enum    attr, type
  else raise ArgumentError, "unknown type coercion %p" % [type]
  end
end

.boolean(attr) ⇒ Object



38
39
40
41
# File 'lib/net/imap/config/attr_type_coercion.rb', line 38

def self.boolean(attr)
  define_method :"#{attr}=" do |val| super !!val end
  define_method :"#{attr}?" do send attr end
end

.enum(attr, enum) ⇒ Object



47
48
49
50
51
52
53
54
55
56
# File 'lib/net/imap/config/attr_type_coercion.rb', line 47

def self.enum(attr, enum)
  enum = enum.dup.freeze
  expected = -"one of #{enum.map(&:inspect).join(", ")}"
  define_method :"#{attr}=" do |val|
    unless enum.include?(val)
      raise ArgumentError, "expected %s, got %p" % [expected, val]
    end
    super val
  end
end

.integer(attr) ⇒ Object



43
44
45
# File 'lib/net/imap/config/attr_type_coercion.rb', line 43

def self.integer(attr)
  define_method :"#{attr}=" do |val| super Integer val end
end