Module: Net::Validations

Included in:
Record
Defined in:
lib/net/validations.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

IP_REGEXP =
/^(\d{1,3}\.){3}\d{1,3}$/
MAC_REGEXP =
/^([a-f0-9]{1,2}:){5}[a-f0-9]{1,2}$/i

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.normalize_ip(ip) ⇒ Object

ensures that the ip address does not contain any leading spaces or invalid strings


31
32
33
34
# File 'lib/net/validations.rb', line 31

def self.normalize_ip ip
  return unless ip.present?
  ip.split(".").map(&:to_i).join(".")
end

.normalize_mac(mac) ⇒ Object


36
37
38
39
40
41
42
43
44
45
# File 'lib/net/validations.rb', line 36

def self.normalize_mac mac
  return unless mac.present?
  m = mac.downcase
  case m
    when /[a-f0-9]{12}/
      m.gsub(/(..)/) { |mh| mh + ":" }[/.{17}/]
    when /([a-f0-9]{1,2}:){5}[a-f0-9]{1,2}/
      m.split(":").map { |nibble| "%02x" % ("0x" + nibble) }.join(":")
  end
end

Instance Method Details

#validate_ip(ip) ⇒ Object

validates the ip address

Raises:


10
11
12
13
# File 'lib/net/validations.rb', line 10

def validate_ip ip
  raise Error, "Invalid IP Address #{ip}" unless (ip =~ IP_REGEXP)
  ip
end

#validate_mac(mac) ⇒ Object

validates the mac

Raises:


16
17
18
19
# File 'lib/net/validations.rb', line 16

def validate_mac mac
  raise Error, "Invalid MAC #{mac}" unless (mac =~ MAC_REGEXP)
  mac
end

#validate_network(network) ⇒ Object


21
22
23
24
25
26
27
28
# File 'lib/net/validations.rb', line 21

def validate_network network
  begin
    validate_ip(network)
  rescue Error
    raise Error, "Invalid Network #{network}"
  end
  network
end