PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/validators/validates_ip_address.rb

https://github.com/willian/validators
Ruby | 47 lines | 36 code | 5 blank | 6 comment | 6 complexity | fffa57f2f4bd2eadf3405c385bb9312b MD5 | raw file
  1. module ActiveModel
  2. module Validations
  3. class IpAddressValidator < EachValidator
  4. def validate_each(record, attribute, value)
  5. return if value.blank? && options[:allow_blank]
  6. return if value.nil? && options[:allow_nil]
  7. valid = false
  8. case options[:only]
  9. when :v4
  10. valid = Validators::Ip.v4?(value.to_s)
  11. scope = :invalid_ipv4_address
  12. when :v6
  13. valid = Validators::Ip.v6?(value.to_s)
  14. scope = :invalid_ipv6_address
  15. else
  16. valid = Validators::Ip.valid?(value.to_s)
  17. scope = :invalid_ip_address
  18. end
  19. unless valid
  20. record.errors.add(
  21. attribute, scope,
  22. :message => options[:message], :value => value
  23. )
  24. end
  25. end
  26. def check_validity!
  27. raise ArgumentError, ":only accepts a symbol that can be either :v6 or :v4" if options.key?(:only) && ![:v4, :v6].include?(options[:only])
  28. end
  29. end
  30. module ClassMethods
  31. # Validates weather or not the specified URL is valid.
  32. #
  33. # validates_ip_address :ip #=> accepts both v4 and v6
  34. # validates_ip_address :ip, :only => :v4
  35. # validates_ip_address :ip, :only => :v6
  36. #
  37. def validates_ip_address(*attr_names)
  38. validates_with IpAddressValidator, _merge_attributes(attr_names)
  39. end
  40. end
  41. end
  42. end