Class: Guillotine::MongoAdapter

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

Instance Method Summary collapse

Methods inherited from Adapter

#get_code, #parse_url, #shorten, #shorten_fixed_charset

Constructor Details

#initialize(collection) ⇒ MongoAdapter

Returns a new instance of MongoAdapter.



5
6
7
8
9
10
11
12
13
14
# File 'lib/guillotine/adapters/mongo_adapter.rb', line 5

def initialize(collection)
  @collection = collection
  @collection.ensure_index([['url',  Mongo::ASCENDING]])

  # \m/
  @transformers = {
    :url => lambda { |doc| doc['url'] },
    :code => lambda { |doc| doc['_id'] }
  }
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.



24
25
26
# File 'lib/guillotine/adapters/mongo_adapter.rb', line 24

def add(url, code = nil, options = nil)
  code_for(url) || insert(url, get_code(url, code, options))
end

#clear(url) ⇒ Object

Public: Removes the assigned short code for a URL.

url - The String URL to remove.

Returns nothing.



52
53
54
# File 'lib/guillotine/adapters/mongo_adapter.rb', line 52

def clear(url)
  @collection.remove(:url => url)
end

#clear_code(code) ⇒ Object

Public: Removes the assigned short code.

code - The String code to remove.

Returns nothing.



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

def clear_code(code)
  @collection.remove(:_id => code)
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.



43
44
45
# File 'lib/guillotine/adapters/mongo_adapter.rb', line 43

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, or nil if none is found.



34
35
36
# File 'lib/guillotine/adapters/mongo_adapter.rb', line 34

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

#select(field, query) ⇒ Object



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

def select(field, query)
  @collection.find_one(query, {:transformer => @transformers[field]})
end