Class: Polipus::Storage::MongoStore

Inherits:
Base
  • Object
show all
Defined in:
lib/polipus/storage/mongo_store.rb

Constant Summary collapse

BINARY_FIELDS =
%w(body headers data)

Instance Attribute Summary

Attributes inherited from Base

#include_query_string_in_uuid

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ MongoStore

Returns a new instance of MongoStore.



8
9
10
11
12
13
14
15
16
# File 'lib/polipus/storage/mongo_store.rb', line 8

def initialize(options = {})
  @mongo      = options[:mongo]
  @collection = options[:collection]
  @mongo.create_collection(@collection)
  @mongo[@collection].ensure_index(:uuid, unique: true, drop_dups: true, background: true)
  @compress_body = options[:compress_body] ||= true
  @except = options[:except] ||= []
  @semaphore = Mutex.new
end

Instance Method Details

#add(page) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/polipus/storage/mongo_store.rb', line 18

def add(page)
  @semaphore.synchronize do
    obj = page.to_hash
    @except.each { |e| obj.delete e.to_s }
    obj['uuid'] = uuid(page)
    obj['body'] = Zlib::Deflate.deflate(obj['body']) if @compress_body && obj['body']
    BINARY_FIELDS.each do |field|
      obj[field] = BSON::Binary.new(obj[field]) unless obj[field].nil?
    end
    @mongo[@collection].update({ uuid: obj['uuid'] }, obj, upsert: true, w: 1)
    obj['uuid']
  end
end

#clearObject



65
66
67
# File 'lib/polipus/storage/mongo_store.rb', line 65

def clear
  @mongo[@collection].drop
end

#countObject



52
53
54
# File 'lib/polipus/storage/mongo_store.rb', line 52

def count
  @mongo[@collection].count
end

#eachObject



56
57
58
59
60
61
62
63
# File 'lib/polipus/storage/mongo_store.rb', line 56

def each
  @mongo[@collection].find({}, timeout: false) do |cursor|
    cursor.each do |doc|
      page = load_page(doc)
      yield doc['uuid'], page
    end
  end
end

#exists?(page) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
# File 'lib/polipus/storage/mongo_store.rb', line 32

def exists?(page)
  @semaphore.synchronize do
    doc = @mongo[@collection].find({ uuid: uuid(page) }, { fields: [:_id] }).limit(1).first
    !doc.nil?
  end
end

#get(page) ⇒ Object



39
40
41
42
43
44
# File 'lib/polipus/storage/mongo_store.rb', line 39

def get(page)
  @semaphore.synchronize do
    data = @mongo[@collection].find(uuid: uuid(page)).limit(1).first
    return load_page(data) if data
  end
end

#remove(page) ⇒ Object



46
47
48
49
50
# File 'lib/polipus/storage/mongo_store.rb', line 46

def remove(page)
  @semaphore.synchronize do
    @mongo[@collection].remove(uuid: uuid(page))
  end
end