Class: Guillotine::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.



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

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.



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

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.



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

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.



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

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.



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

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

#select(field, query) ⇒ Object



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

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

#setupObject



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

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

    unique :url
    unique :code
  end
end