Class: Guillotine::Adapters::SequelAdapter

Inherits:
Adapter
  • Object
show all
Defined in:
lib/guillotine/adapters/sequel_adapter.rb

Instance Method Summary collapse

Methods inherited from Adapter

#parse_url, #shorten

Constructor Details

#initialize(db) ⇒ SequelAdapter

Returns a new instance of SequelAdapter.



4
5
6
7
# File 'lib/guillotine/adapters/sequel_adapter.rb', line 4

def initialize(db)
  @db = db
  @table = @db[:urls]
end

Instance Method Details

#add(url, code = nil) ⇒ Object

Public: Stores the shortened version of a URL.

url - The String URL to shorten and store. code - Optional String code for the URL.

Returns the unique String code for the URL. If the URL is added multiple times, this should return the same code.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/guillotine/adapters/sequel_adapter.rb', line 16

def add(url, code = nil)
  if existing = code_for(url)
    existing
  else
    code ||= shorten url
    begin
      @table << {:url => url, :code => code}
    rescue Sequel::DatabaseError
      if existing_url = @table.select(:url).where(:code => code).first
        raise DuplicateCodeError.new(existing_url, url, code)
      else
        raise
      end
    end
    code
  end
end

#clear(url) ⇒ Object

Public: Removes the assigned short code for a URL.

url - The String URL to remove.

Returns nothing.



57
58
59
# File 'lib/guillotine/adapters/sequel_adapter.rb', line 57

def clear(url)
  @table.where(:url => url).delete
end

#code_for(url) ⇒ Object

Public: Retrieves the code for a given URL.

url - The String URL to lookup.

Returns the String code, or nil if none is found.



48
49
50
# File 'lib/guillotine/adapters/sequel_adapter.rb', line 48

def code_for(url)
  select :code, :url => url
end

#find(code) ⇒ Object

Public: Retrieves a URL from the code.

code - The String code to lookup the URL.

Returns the String URL.



39
40
41
# File 'lib/guillotine/adapters/sequel_adapter.rb', line 39

def find(code)
  select :url, :code => code
end

#select(field, query) ⇒ Object



71
72
73
74
75
# File 'lib/guillotine/adapters/sequel_adapter.rb', line 71

def select(field, query)
  if row = @table.select(field).where(query).first
    row[field]
  end
end

#setupObject



61
62
63
64
65
66
67
68
69
# File 'lib/guillotine/adapters/sequel_adapter.rb', line 61

def setup
  @db.create_table :urls do
    String :url
    String :code

    unique :url
    unique :code
  end
end