Forum: Ruby on Rails Netmask validator

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Jeremy M. (Guest)
on 2006-04-12 21:06
(Received via mailing list)
Sharing the wealth. I just finished working on a custom netmask
validator and thought others might benefit. Of course, comments and
suggestions are welcome.

def validates_netmask(*attr_names)
  configuration = { :only_numbers => 'must only use numbers as octet
                    :range => 'has one or more octet values that are >
                    :invalid => 'is invalid' }
  configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)

  validates_each attr_names do |record, attr_name, value|
    # Test for non-numeric values
    record.errors.add(attr_name, configuration[:only_numbers]) unless'.', '') =~ /^\d+$/

    # Make binary string from octets
    binary = ''
    value.split('.').each do |octet|
      binary << '%08b' % octet

    # Test for octet values > 255
    record.errors.add(attr_name, configuration[:range]) if binary.length
> 32

    # Test for valid netmask (contiguous binary string of 1's)
    record.errors.add(attr_name, configuration[:invalid]) if
binary.include? '01'
This topic is locked and can not be replied to.