Class: LongURL::Service

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

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Service

Returns a new instance of Service.



14
15
16
17
18
19
20
21
22
23
# File 'lib/longurl/service.rb', line 14

def initialize(params = {})
  if params[:cache].nil?
    @@cache = Hash.new
  elsif params[:cache] == false
    @@cache = nil
  else
    @@cache = params[:cache]
  end
  @@supported_services = cached_or_fetch_supported_services
end

Instance Method Details

#cached_query(url) ⇒ Object



31
32
33
# File 'lib/longurl/service.rb', line 31

def cached_query(url)
  @@cache[url] ||= query(url)
end

#query(url) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/longurl/service.rb', line 35

def query(url)
  escaped_url = check_and_escape(url)
  Net::HTTP.start(EndPoint.host, EndPoint.port) do |http|
    handle_response http.get("#{EndPoint.path}?format=json&url=#{escaped_url}")
  end
rescue Timeout::Error, Errno::ENETUNREACH, Errno::ETIMEDOUT, SocketError
  raise LongURL::NetworkError
end

#query_supported_service_only(url) ⇒ Object



25
26
27
28
29
# File 'lib/longurl/service.rb', line 25

def query_supported_service_only(url)
  check url
  raise LongURL::UnsupportedService unless service_supported?(url)
  (@@cache && cached_query(url)) || query(url)
end

#service_supported?(url) ⇒ Boolean

Check among supported services by longurl.org if given url is supported. Returns true if supported, false otherwise.

Returns:

  • (Boolean)


46
47
48
# File 'lib/longurl/service.rb', line 46

def service_supported?(url)
  @@supported_services.include? URI.parse(url).host.downcase
end