Class: Guillotine::RedisAdapter

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

Instance Method Summary collapse

Methods inherited from Adapter

#parse_url, #shorten

Constructor Details

#initialize(redis) ⇒ RedisAdapter

Public: Initialise the adapter with a Redis instance.

redis - A Redis instance to persist urls and codes to.



6
7
8
# File 'lib/guillotine/adapters/redis_adapter.rb', line 6

def initialize(redis)
  @redis = redis
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.



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

def add(url, code = nil)
  if existing_code = @redis.get(url_key(url))
    existing_code
  else
    code ||= shorten(url)
    if existing_url = @redis.get(code_key(code))
      raise DuplicateCodeError.new(existing_url, url, code) if url != existing_url
    end
    @redis.set code_key(code), url
    @redis.set url_key(url), code
    code
  end
end

#clear(url) ⇒ Object

Public: Removes the assigned short code for a URL.

url - The String URL to remove.

Returns nothing.



54
55
56
57
58
59
# File 'lib/guillotine/adapters/redis_adapter.rb', line 54

def clear(url)
  if code = @redis.get(url_key(url))
    @redis.del url_key(url)
    @redis.del code_key(code)
  end
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.



45
46
47
# File 'lib/guillotine/adapters/redis_adapter.rb', line 45

def code_for(url)
  @redis.get url_key(url)
end

#code_key(code) ⇒ Object



61
62
63
# File 'lib/guillotine/adapters/redis_adapter.rb', line 61

def code_key(code)
  "guillotine:hash:#{code}"
end

#find(code) ⇒ Object

Public: Retrieves a URL from the code.

code - The String code to lookup the URL.

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



36
37
38
# File 'lib/guillotine/adapters/redis_adapter.rb', line 36

def find(code)
  @redis.get code_key(code)
end

#url_key(url) ⇒ Object



65
66
67
# File 'lib/guillotine/adapters/redis_adapter.rb', line 65

def url_key(url)
  "guillotine:urls:#{url}"
end