lib/better_ipaddr/classes.rb in better_ipaddr-0.2.3 vs lib/better_ipaddr/classes.rb in better_ipaddr-0.3.0
- old
+ new
@@ -1,18 +1,15 @@
+require "better_ipaddr/constants"
require "better_ipaddr/methods"
class IPAddr
class Base < IPAddr
include BetterIpaddr::Constants
include BetterIpaddr::InstanceMethods
include Comparable
include Enumerable
- def inherited(cls)
- cls.extend BetterIpaddr::ClassMethods
- end
-
# Create an IPAddr from the given object.
#
# Returns nil if the object is of a type that can't be converted to an
# IPAddr.
#
@@ -31,10 +28,33 @@
when String
from_string(address, prefix_length, family: family)
end
end
+ # Create an IPAddr from the given object, guessing the type of address given
+ # based on its type and content.
+ #
+ # Note that an Integer that corresponds to an IPv4 address will be converted
+ # to an IPAddr::V4, even though all such Integers also correspond to valid
+ # IPv6 addresses.
+ #
+ # Returns nil if the object can't be converted based on its type and
+ # content.
+ #
+ # @param address [Integer, IPAddr, String]
+ # @return [IPAddr, Nil]
+ def self.from(address)
+ case address
+ when IPAddr
+ specialize address
+ when Regex::IPV4, 0..V4::MAX_INT
+ V4[address]
+ when Regex::IPV6, 0..V6::MAX_INT
+ V6[address]
+ end
+ end
+
# Create an IPAddr from an Integer.
#
# @param address [Integer]
# @param mask [Integer, String] a netmask or prefix length
# @param family [Integer, Nil]
@@ -170,10 +190,11 @@
const_set(:BIT_LENGTH, FAMILY_TO_BIT_LENGTH.fetch(self::FAMILY))
const_set(:NETMASK_TO_PREFIX_LENGTH,
NETMASK_TO_PREFIX_LENGTH.fetch(self::FAMILY))
const_set(:PREFIX_LENGTH_TO_NETMASK,
PREFIX_LENGTH_TO_NETMASK.fetch(self::FAMILY))
+ const_set(:MAX_INT, 2**self::BIT_LENGTH - 1)
end
def address_family_bit_length
self.class::BIT_LENGTH
end
@@ -187,13 +208,17 @@
end
end
class V4 < Base
specialize_constants Family::IPV4
+
+ REGEX = Regex::IPV4
end
class V6 < Base
specialize_constants Family::IPV6
+
+ REGEX = Regex::IPV6
end
class MAC < Base
specialize_constants Family::EUI48
end