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



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

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

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



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

def hash
  @hash
end

#urlsObject (readonly)

Returns the value of attribute urls.



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

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.



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

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.



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

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.



46
47
48
# File 'lib/guillotine/adapters/memory_adapter.rb', line 46

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.



37
38
39
# File 'lib/guillotine/adapters/memory_adapter.rb', line 37

def find(code)
  @hash[code]
end