Class: Expurrel

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

Overview

Expurrel is a tiny url that can be decoded.

Constant Summary collapse

PROVIDERS =
[]
PROVIDERS_LIST_FILE =
File.join(File.dirname(__FILE__), '..', 'tinyurlproviders.txt')
@@cache =
SimpleCache.new(:max_size => 1000)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url) ⇒ Expurrel

Give expurrel a new url



14
15
16
# File 'lib/expurrel.rb', line 14

def initialize(url)
  @url = url
end

Class Method Details

.load_providers!Object

Loads the list with providers into the PROVIDERS constant.



71
72
73
74
75
76
# File 'lib/expurrel.rb', line 71

def load_providers!
  return if !PROVIDERS.empty?
  File.open(PROVIDERS_LIST_FILE, "r") .each_line do |line|
    PROVIDERS << line
  end
end

.reverse_tinyurl(tinyurl) ⇒ Object

Uses the header file sent back to decode the tiny url. Trick provided by: garrickvanburen.com/archive/how-to-decode-tinyurls-with-ruby



85
86
87
# File 'lib/expurrel.rb', line 85

def reverse_tinyurl(tinyurl)
  Net::HTTP.get_response(URI.parse(tinyurl)).to_hash['location'].to_s
end

Instance Method Details

#decodeObject

This method checks first if it’s a tiny url domain from the list.

  1. Is it a tinyurl?

  2. It is cached? (tinyurls won’t change we can cache forever)

  3. Decode (slow!), does http request.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/expurrel.rb', line 23

def decode
  return begin
    if !self.is_tiny_url?
      @url
    elsif @@cache.has_key?(@url)
      @@cache.value(@url)
    else
      # TODO add it to the cache
      decoded_url = self.class.reverse_tinyurl(@url)
      @@cache.cache!(@url, decoded_url)
      decoded_url
    end
  end
end

#domainObject

Get the domain



59
60
61
62
63
64
# File 'lib/expurrel.rb', line 59

def domain
  return @domain if !@domain.nil? 
  unpacked_link = @url.scan(/(https?:\/\/|www\.)([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?/)
  @domain = unpacked_link.first[1]
  return @domain
end

#is_tiny_domain?(domain) ⇒ Boolean

Is it a tiny domain?

Returns:

  • (Boolean)


46
47
48
49
50
51
52
53
54
# File 'lib/expurrel.rb', line 46

def is_tiny_domain?(domain)
  PROVIDERS.each do |l|
    # TODO regular expression matching
    if domain.include?(l)
      return true
    end
  end
  false
end

#is_tiny_url?Boolean

Is this a tiny url

Returns:

  • (Boolean)


40
41
42
# File 'lib/expurrel.rb', line 40

def is_tiny_url?
  is_tiny_domain?(self.domain)
end