class Coppertone::Mechanism::IPMechanism

Implements the ip4 mechanism.

Constants

IP_PARSE_ERROR

Hack for JRuby - remove when JRuby moves to 2.0.x

LEADING_ZEROES_IN_CIDR_REGEXP

Attributes

cidr_length[R]
netblock[R]

Public Class Methods

create(attributes) click to toggle source
# File lib/coppertone/mechanism/ip_mechanism.rb, line 7
def self.create(attributes)
  new(attributes)
end
new(attributes) click to toggle source
Calls superclass method Coppertone::Mechanism::new
# File lib/coppertone/mechanism/ip_mechanism.rb, line 11
def initialize(attributes)
  super(attributes)
  unless attributes.blank?
    attributes = attributes[1..] if attributes[0] == ':'
    @netblock, @cidr_length = parse_netblock(attributes)
  end
  raise Coppertone::InvalidMechanismError if @netblock.nil?
end

Public Instance Methods

==(other) click to toggle source
# File lib/coppertone/mechanism/ip_mechanism.rb, line 59
def ==(other)
  return false unless other.instance_of? self.class

  netblock == other.netblock
end
default_cidr(network) click to toggle source
# File lib/coppertone/mechanism/ip_mechanism.rb, line 47
def default_cidr(network)
  network.ipv6? ? 128 : 32
end
match?(macro_context, _request_context) click to toggle source
# File lib/coppertone/mechanism/ip_mechanism.rb, line 51
def match?(macro_context, _request_context)
  ip = ip_for_match(macro_context)
  return false unless ip
  return false unless ip.ipv4? == @netblock.ipv4?

  @netblock.include?(ip)
end
parse_netblock(ip_as_s) click to toggle source
# File lib/coppertone/mechanism/ip_mechanism.rb, line 34
def parse_netblock(ip_as_s)
  validate_no_leading_zeroes_in_cidr(ip_as_s)
  addr, cidr_length_as_s, dual = ip_as_s.split('/')
  return [nil, nil] if dual

  network = IPAddr.new(addr)
  network = network.mask(cidr_length_as_s.to_i) unless cidr_length_as_s.blank?
  cidr_length = cidr_length_as_s.blank? ? default_cidr(network) : cidr_length_as_s.to_i
  [network, cidr_length]
rescue IP_PARSE_ERROR
  [nil, nil]
end
validate_no_leading_zeroes_in_cidr(ip_as_s) click to toggle source
# File lib/coppertone/mechanism/ip_mechanism.rb, line 21
def validate_no_leading_zeroes_in_cidr(ip_as_s)
  return unless LEADING_ZEROES_IN_CIDR_REGEXP.match?(ip_as_s)

  raise Coppertone::InvalidMechanismError
end