Class: Anemone::Storage::MongoDB
- Inherits:
-
Object
- Object
- Anemone::Storage::MongoDB
- Defined in:
- lib/anemone/storage/mongodb.rb
Constant Summary collapse
- BINARY_FIELDS =
%w(body headers data)
Instance Method Summary collapse
- #[](url) ⇒ Object
- #[]=(url, page) ⇒ Object
- #close ⇒ Object
- #delete(url) ⇒ Object
- #each ⇒ Object
- #has_key?(url) ⇒ Boolean
-
#initialize(mongo_db, collection_name) ⇒ MongoDB
constructor
A new instance of MongoDB.
- #keys ⇒ Object
- #merge!(hash) ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize(mongo_db, collection_name) ⇒ MongoDB
Returns a new instance of MongoDB.
14 15 16 17 18 19 |
# File 'lib/anemone/storage/mongodb.rb', line 14 def initialize(mongo_db, collection_name) @db = mongo_db @collection = @db[collection_name] @collection.remove @collection.create_index 'url' end |
Instance Method Details
#[](url) ⇒ Object
21 22 23 24 25 |
# File 'lib/anemone/storage/mongodb.rb', line 21 def [](url) if value = @collection.find_one('url' => url.to_s) load_page(value) end end |
#[]=(url, page) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/anemone/storage/mongodb.rb', line 27 def []=(url, page) hash = page.to_hash BINARY_FIELDS.each do |field| hash[field] = BSON::Binary.new(hash[field]) unless hash[field].nil? end @collection.update( {'url' => page.url.to_s}, hash, :upsert => true ) end |
#close ⇒ Object
73 74 75 |
# File 'lib/anemone/storage/mongodb.rb', line 73 def close @db.connection.close end |
#delete(url) ⇒ Object
39 40 41 42 43 |
# File 'lib/anemone/storage/mongodb.rb', line 39 def delete(url) page = self[url] @collection.remove('url' => url.to_s) page end |
#each ⇒ Object
45 46 47 48 49 50 51 52 |
# File 'lib/anemone/storage/mongodb.rb', line 45 def each @collection.find do |cursor| cursor.each do |doc| page = load_page(doc) yield page.url.to_s, page end end end |
#has_key?(url) ⇒ Boolean
69 70 71 |
# File 'lib/anemone/storage/mongodb.rb', line 69 def has_key?(url) !!@collection.find_one('url' => url.to_s) end |
#keys ⇒ Object
63 64 65 66 67 |
# File 'lib/anemone/storage/mongodb.rb', line 63 def keys keys = [] self.each { |k, v| keys << k.to_s } keys end |
#merge!(hash) ⇒ Object
54 55 56 57 |
# File 'lib/anemone/storage/mongodb.rb', line 54 def merge!(hash) hash.each { |key, value| self[key] = value } self end |
#size ⇒ Object
59 60 61 |
# File 'lib/anemone/storage/mongodb.rb', line 59 def size @collection.count end |