Permalink
Browse files

Added basic mongodb support.

Added basic mongodb support. Removed 'moneta/file' from spec_helper.rb because it was giving me libSystem.dylib failures on my system, though. Not sure why it was happenning to me.
  • Loading branch information...
aemadrid committed Apr 23, 2009
1 parent 761e877 commit a26834644c211323bdaed17168c4d8a6aa3f55a3
Showing with 78 additions and 3 deletions.
  1. +2 −1 .gitignore
  2. +62 −0 lib/moneta/mongodb.rb
  3. +12 −0 spec/moneta_mongodb_spec.rb
  4. +2 −2 spec/spec_helper.rb
View
@@ -1 +1,2 @@
-moneta-*.gem
+moneta-*.gem
+.idea
View
@@ -0,0 +1,62 @@
+begin
+ require "mongo"
+rescue LoadError
+ puts "You need the mongo gem to use the MongoDB moneta store"
+ exit
+end
+
+module Moneta
+ class MongoDB
+ def initialize(options = {})
+ options = {
+ :host => ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost',
+ :port => ENV['MONGO_RUBY_DRIVER_PORT'] || XGen::Mongo::Driver::Mongo::DEFAULT_PORT,
+ :db => 'cache',
+ :collection => 'cache'
+ }.update(options)
+ conn = XGen::Mongo::Driver::Mongo.new(options[:host], options[:port])
+ @cache = conn.db(options[:db]).collection(options[:collection])
+ end
+
+ def key?(key)
+ !!self[key]
+ end
+
+ alias has_key? key?
+
+ def [](key)
+ res = @cache.find_first('_id' => key)
+ res = nil if res && res['expires'] && Time.now > res['expires']
+ res && res['data']
+ end
+
+ def []=(key, value)
+ store(key, value)
+ end
+
+ def fetch(key, default)
+ self[key] || default
+ end
+
+ def delete(key)
+ value = self[key]
+ @cache.remove('_id' => key) if value
+ value
+ end
+
+ def store(key, value, options = {})
+ exp = options[:expires_in] ? (Time.now + options[:expires_in]) : nil
+ @cache.repsert({ '_id' => key }, { '_id' => key, 'data' => value, 'expires' => exp })
+ end
+
+ def update_key(key, options = {})
+ val = self[key]
+ self.store(key, val, options)
+ end
+
+ def clear
+ @cache.clear
+ end
+ end
+end
+
@@ -0,0 +1,12 @@
+require File.dirname(__FILE__) + '/spec_helper'
+require "moneta/mongodb"
+
+describe "Moneta::MongoDB" do
+ before(:each) do
+ @native_expires = true
+ @cache = Moneta::MongoDB.new
+ @cache.clear
+ end
+
+ it_should_behave_like "a read/write Moneta cache"
+end
View
@@ -4,6 +4,6 @@
require "rubygems"
require "moneta"
require "moneta/memory"
-require "moneta/file"
+#require "moneta/file"
-require File.expand_path(File.join(File.dirname(__FILE__), "shared"))
+require File.expand_path(File.join(File.dirname(__FILE__), "shared"))

0 comments on commit a268346

Please sign in to comment.