Class: Truncator::UrlParser

Inherits:
Object
  • Object
show all
Defined in:
lib/truncator/url_parser.rb

Constant Summary collapse

SEPARATOR =
'...'

Class Method Summary collapse

Class Method Details

.shorten_url(uri, truncation_length = 42) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/truncator/url_parser.rb', line 11

def shorten_url(uri, truncation_length = 42)
  begin
    uri = URI(uri)
  rescue URI::InvalidURIError
    uri = uri.sub(/\Ahttp:\/\//, '') # remove http protocol
    return uri.truncate(truncation_length)
  end

  if !uri.ordinary_hostname?
    if uri.query
      uri.query_parameters = [uri.query_parameters.first]
      return uri.to_s + SEPARATOR
    else
      return uri.to_s
    end
  end

  return uri.special_format if uri.special_format.valid_length?(truncation_length)

  if uri.path_blank? && !uri.query
    return uri.special_format.truncate!(truncation_length)
  end

  if uri.query
    return uri.special_format.truncate!(truncation_length)
  else
    if uri.host.valid_length?(truncation_length)
      result = truncate_by_shortest(uri, truncation_length)
      if result
        uri = result
      else
        return uri.special_format.truncate!(truncation_length)
      end
    else
      return uri.special_format.truncate!(truncation_length)
    end
  end

  uri.special_format

rescue Truncator::ExtendedURI::QueryParamWithoutValueError # for ruby <2.1.0 r40460
  return uri.to_s.truncate(truncation_length)
end