Module: IPAddressSerializer

Defined in:
lib/ip_address_serializer2.rb

Overview

This is the main module. It is called IPAddressSerializer to maintain compatability with the original project, nowever, as it now relies on a custom fork of the ruby-ip library, then gem is called something different

Defined Under Namespace

Classes: Error

Class Method Summary collapse

Class Method Details

.dump(value) ⇒ String

Save the value, which converts either a String, or an IP Object to the String representation for storage

Parameters:

  • String (String, IP, IP::V4, IP::V6)

    representation, or internal IP representation of an IP Address

Returns:

  • (String)

    The encoded string value representing the IP address object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/ip_address_serializer2.rb', line 40

def self.dump(value)
  return nil if value.nil?

  case value
  when String
    ip = IP.new(value)
  when IP, IP::V4, IP::V6
    ip = value
  end
  address = nil
  if ip.proto == 'v4'
    rawhex = ip.to_hex
    address = rawhex[0..1] + V4DELIMITER +
              rawhex[2..3] + V4DELIMITER +
              rawhex[4..5] + V4DELIMITER +
              rawhex[6..7]
  end
  if ip.proto == 'v6'
    rawhex = ip.to_hex
    address = rawhex[0..3] + V6DELIMITER +
              rawhex[4..7] + V6DELIMITER +
              rawhex[8..11] + V6DELIMITER +
              rawhex[12..15] + V6DELIMITER +
              rawhex[16..19] + V6DELIMITER +
              rawhex[20..23] + V6DELIMITER +
              rawhex[24..27] + V6DELIMITER +
              rawhex[28..31]
  end
  if ip.ctx.nil?
    [ip.proto, address, ip.pfxlen].join(DELIMITER)
  else
    ctext = CTXDELIMITER + ip.ctx.to_s
    [ip.proto, address, ip.pfxlen, ctext].join(DELIMITER)
  end
end

.load(value) ⇒ IP

Load the value and return the IP Object.

Parameters:

  • value (String)

    String representation of the IP Object

Returns:

  • (IP)

    The IP Object (from ruby-ip)



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/ip_address_serializer2.rb', line 20

def self.load(value)
  return nil if value.nil?

  ctext = nil
  if value.is_a?(String) && value.index(CTXDELIMITER)
    ctext = value.split(CTXDELIMITER)[1]
    value = value.split(CTXDELIMITER)[0]
  end
  if value.is_a?(String) && value.index(DELIMITER)
    value = value.gsub(V4DELIMITER, '') if value[1] == '4' && value.index(V4DELIMITER)
    value = value.gsub(V6DELIMITER, '') if value[1] == '6' && value.index(V6DELIMITER)
    ip = IP.new(value.split(DELIMITER))
    ip.ctx = ctext if ctext
    ip
  end
end