Class: Guillotine::MemoryAdapter

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

Overview

Stores shortened URLs in memory. Totally scales.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Adapter

#parse_url, #shorten

Constructor Details

#initializeMemoryAdapter

Returns a new instance of MemoryAdapter.



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

def initialize
  reset
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



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

def hash
  @hash
end

#urlsObject (readonly)

Returns the value of attribute urls.



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

def urls
  @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
# File 'lib/guillotine/adapters/memory_adapter.rb', line 16

def add(url, code = nil)
  if existing_code = @urls[url]
    existing_code
  else
    code ||= shorten(url)
    if existing_url = @hash[code]
      raise DuplicateCodeError.new(existing_url, url, code) if url != existing_url
    end
    @hash[code] = url
    @urls[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.



53
54
55
56
57
# File 'lib/guillotine/adapters/memory_adapter.rb', line 53

def clear(url)
  if code = @urls.delete(url)
    @hash.delete 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.



44
45
46
# File 'lib/guillotine/adapters/memory_adapter.rb', line 44

def code_for(url)
  @urls[url]
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.



35
36
37
# File 'lib/guillotine/adapters/memory_adapter.rb', line 35

def find(code)
  @hash[code]
end

#resetObject



59
60
61
62
# File 'lib/guillotine/adapters/memory_adapter.rb', line 59

def reset
  @hash = {}
  @urls = {}
end