Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/anemone/storage.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ def self.MongoDB(mongo_db = nil, collection_name = 'pages')
self::MongoDB.new(mongo_db, collection_name)
end

def self.Mongoid(model_name = 'anemone')
require 'anemone/storage/mongoid'
self::Mongoid.new(model_name)
end

def self.Redis(opts = {})
require 'anemone/storage/redis'
self::Redis.new(opts)
Expand Down
77 changes: 77 additions & 0 deletions lib/anemone/storage/mongoid.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
begin
require 'mongoid'
rescue LoadError
puts "You need the mongoid gem to use Anemone::Storage::Mongoid"
exit
end

module Anemone
module Storage
class Mongoid

BINARY_FIELDS = %w(body headers data)

def initialize(model_name)
@model = model_name.is_a?(String) ? model_name.classify.constantize : model_name
@model.destroy_all
@model.create_indexes #'url'
end

def [](url)
if value = @model.where(:url => url.to_s).first
load_page(value)
end
end

def []=(url, page)
hash = page.to_hash
BINARY_FIELDS.each do |field|
hash[field] = Moped::BSON::Binary.new(:generic, hash[field]) unless hash[field].nil?
end
@model.find_or_create_by(:url => page.url.to_s).update(hash)
end

def delete(url)
page = self[url]
@model.destroy(:url => url.to_s)
page
end

def each
@model.each do |doc|
page = load_page(doc)
yield page.url.to_s, page
end
end

def merge!(hash)
hash.each { |key, value| self[key] = value }
self
end

def size
@model.count
end

def keys
keys = []
self.each { |k, v| keys << k.to_s }
keys
end

def has_key?(url)
!!@model.where(:url => url.to_s).first
end

private

def load_page(doc)
BINARY_FIELDS.each do |field|
doc.send(field) = doc.send(field).to_s
end
Page.from_hash(doc)
end

end
end
end