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
--
Posted with http://DevLists.com. Sign up and save your mailbox.