Class: Murlsh::RandomServer

Inherits:
Server
  • Object
show all
Defined in:
lib/murlsh/random_server.rb

Overview

Redirect to a random url from the database.

Instance Attribute Summary

Attributes inherited from Server

#config

Instance Method Summary collapse

Methods inherited from Server

#initialize

Constructor Details

This class inherits a constructor from Murlsh::Server

Instance Method Details

#get(req) ⇒ Object

Redirect to a random url from the database optionally matching a query.

Redirect to root url if no urls match.



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

def get(req)
  all_results = Murlsh::UrlResultSet.new(req['q'], 1, 1)

  url = if all_results.total_entries > 0
    Murlsh::UrlResultSet.new(req['q'],
      rand(all_results.total_entries) + 1, 1).results[0].url
  else
    config.fetch('root_url')
  end

  resp = Rack::Response.new("<a href=\"#{url}\">#{url}</a>")
  resp.redirect(url)

  resp
end