Forum: Ruby on Rails Netmask validator

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5d15c6821f3c3054c04b85471824ba7c?d=identicon&s=25 Jeremy Maziarz (Guest)
on 2006-04-12 19: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
values',
                    :range => 'has one or more octet values that are >
255',
                    :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
value.tr('.', '') =~ /^\d+$/

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

    # 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'
  end
end
This topic is locked and can not be replied to.