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

#get_code, #parse_url, #shorten, #shorten_fixed_charset

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, options = 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. options - Optional Guillotine::Service::Options

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
30
# File 'lib/guillotine/adapters/memory_adapter.rb', line 17

def add(url, code = nil, options = nil)
  if existing_code = @urls[url]
    existing_code
  else
    code = get_code(url, code, options)

    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

#clear_code(code) ⇒ Object

Public: Removes the assigned short code.

code - The String code to remove.

Returns nothing.



66
67
68
69
70
# File 'lib/guillotine/adapters/memory_adapter.rb', line 66

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

#resetObject



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

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