Class: LongURL::Service
- Inherits:
-
Object
- Object
- LongURL::Service
- Defined in:
- lib/longurl/service.rb
Instance Method Summary collapse
- #cached_query(url, options = { }) ⇒ Object
-
#initialize(params = {}) ⇒ Service
constructor
A new instance of Service.
- #query(url, options = { }) ⇒ Object
- #query_supported_service_only(url, options = { }) ⇒ Object
-
#service_supported?(url) ⇒ Boolean
Check among supported services by longurl.org if given
url
is supported.
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, options = { }) ⇒ Object
31 32 33 |
# File 'lib/longurl/service.rb', line 31 def cached_query(url, ={ }) @@cache[url] ||= query(url, ) end |
#query(url, options = { }) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/longurl/service.rb', line 35 def query(url, ={ }) escaped_url = check_and_escape(url) api_url = "#{EndPoint.path}?format=json&url=#{escaped_url}" if [:first_only] api_url += "&all-redirects=1" end Net::HTTP.start(EndPoint.host, EndPoint.port) do |http| handle_response http.get(api_url) end rescue Timeout::Error, Errno::ENETUNREACH, Errno::ETIMEDOUT, SocketError raise LongURL::NetworkError end |
#query_supported_service_only(url, options = { }) ⇒ 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.
50 51 52 |
# File 'lib/longurl/service.rb', line 50 def service_supported?(url) @@supported_services.include? URI.parse(url).host.downcase end |