Class: Unshorter

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_level = 5) ⇒ Unshorter

Returns a new instance of Unshorter.



9
10
11
# File 'lib/unshorter.rb', line 9

def initialize(max_level = 5)
  @max_level = max_level
end

Instance Attribute Details

#max_levelObject (readonly)

Returns the value of attribute max_level.



7
8
9
# File 'lib/unshorter.rb', line 7

def max_level
  @max_level
end

Instance Method Details

#call(url) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/unshorter.rb', line 13

def call(url)
  url = "http://#{url}" if url !~ %r{^(http|https)://}
  original_uri = uri = URI(url)
  max_level.times do
    response = Net::HTTP.get_response(uri)

    if %w[301 302].include?(response.code)
      uri = URI(response["location"])
      next
    end

    if original_uri.host.sub(/www\./, "") == uri.host
      break response.body.scan(%r{location=['|"]([a-z:/\.\d]+)['|"]}).flatten.fetch(0, nil)
    end

    break uri.to_s
  end
end