module NaughtyOrNice

Primary module to be mixed into the child class

Constants

EMAIL_REGEX

Source: bit.ly/1n2X9iv

VERSION

Public Class Methods

included(base) click to toggle source
# File lib/naughty_or_nice.rb, line 55
def self.included(base)
  base.extend(ClassMethods)
end
new(domain) click to toggle source
# File lib/naughty_or_nice.rb, line 59
def initialize(domain)
  if domain.is_a?(PublicSuffix::Domain)
    @domain = domain
    @text   = domain.to_s
  else
    @text = domain.to_s.downcase.strip
  end
end

Public Instance Methods

domain() click to toggle source

Return the public suffix domain object

Supports all domain strings (URLs, emails)

Returns the domain object or nil, but no errors, never an error

# File lib/naughty_or_nice.rb, line 73
def domain
  return @domain if defined? @domain

  @domain = begin
    PublicSuffix.parse(normalized_domain, default_rule: nil)
  rescue PublicSuffix::DomainInvalid, PublicSuffix::DomainNotAllowed
    nil
  end
end
email?() click to toggle source

Is the input text in the form of a valid email address?

Returns true if email, otherwise false

# File lib/naughty_or_nice.rb, line 93
def email?
  !(@text =~ EMAIL_REGEX).nil?
end
inspect() click to toggle source
# File lib/naughty_or_nice.rb, line 102
def inspect
  "#<#{self.class} domain=\"#{domain}\" valid=#{valid?}>"
end
to_s() click to toggle source

Return the parsed domain as a string

# File lib/naughty_or_nice.rb, line 98
def to_s
  @to_s ||= domain.to_s if domain
end
valid?() click to toggle source

Checks if the input string represents a valid domain

Returns boolean true if a valid domain, otherwise false

# File lib/naughty_or_nice.rb, line 86
def valid?
  !domain.nil?
end

Private Instance Methods

normalized_domain() click to toggle source

Parse the domain from the input string

Can handle urls, domains, or emails

Returns the domain string

# File lib/naughty_or_nice.rb, line 113
def normalized_domain
  if @text.empty?
    nil
  elsif parsed_domain
    parsed_domain.host
  end
end
parsed_domain() click to toggle source
# File lib/naughty_or_nice.rb, line 121
def parsed_domain
  @parsed_domain ||= begin
    text = @text.dup
    text.prepend('http://') unless %r{\Ahttps?://}.match?(text)
    uri = Addressable::URI.parse(text)
    # properly parse http://foo edge cases
    # see https://github.com/sporkmonger/addressable/issues/145
    uri if uri.host.include?('.')
  end
rescue Addressable::URI::InvalidURIError
  nil
end