Class: Guillotine::Service

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

Constant Summary collapse

NullChecker =

Deprecated until v2

Guillotine::HostChecker

Instance Method Summary collapse

Constructor Details

#initialize(db, required_host = nil) ⇒ Service

This is the public API to the Guillotine service. Wire this up to Sinatra or whatever. Every public method should return a compatible Rack Response: [Integer Status, Hash headers, String body].

db - A Guillotine::Adapter instance. required_host - Either a String or Regex limiting which domains the

shortened URLs can come from.


14
15
16
17
# File 'lib/guillotine/service.rb', line 14

def initialize(db, required_host = nil)
  @db = db
  @host_check = HostChecker.matching(required_host)
end

Instance Method Details

#check_host(url) ⇒ Object

Checks to see if the input URL is using a valid host. You can constrain the hosts with the ‘required_host` argument of the Service constructor.

url - An Addressible::URI instance to check.

Returns a 422 Rack::Response if the host is invalid, or nil.



63
64
65
66
67
68
69
# File 'lib/guillotine/service.rb', line 63

def check_host(url)
  if url.scheme !~ /^https?$/
    [422, {}, "Invalid url: #{url}"]
  else
    @host_check.call url
  end
end

#create(url, code = nil) ⇒ Object

Public: Maps a URL to a shortened code.

url - A String or Addressable::URI URL to shorten. code - Optional String code to use. Defaults to a random String.

Returns 201 with the Location pointing to the code, or 422.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/guillotine/service.rb', line 39

def create(url, code = nil)
  url = ensure_url(url)

  if resp = check_host(url)
    return resp
  end

  begin
    if code = @db.add(url.to_s, code)
      [201, {"Location" => code}]
    else
      [422, {}, "Unable to shorten #{url}"]
    end
  rescue DuplicateCodeError => err
    [422, {}, err.to_s]
  end
end

#ensure_url(str) ⇒ Object

Ensures that the argument is an Addressable::URI.

str - A String URL or an Addressable::URI.

Returns an Addressable::URI.



76
77
78
79
80
81
82
83
84
85
# File 'lib/guillotine/service.rb', line 76

def ensure_url(str)
  if str.respond_to?(:scheme)
    str
  else
    str = str.to_s
    str.gsub! /\s/, ''
    str.gsub! /(\#|\?).*/, ''
    Addressable::URI.parse str
  end
end

#get(code) ⇒ Object

Public: Gets the full URL for a shortened code.

code - A String short code.

Returns 302 with the Location header pointing to the URL on a hit, or 404 on a miss.



25
26
27
28
29
30
31
# File 'lib/guillotine/service.rb', line 25

def get(code)
  if url = @db.find(code)
    [302, {"Location" => @db.parse_url(url).to_s}]
  else
    [404, {}, "No url found for #{code}"]
  end
end