Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Now marshal's objects so more than strings can be stored.

  • Loading branch information...
commit 70fb026faa7d59a30929edb3cd4da3135fe75b0f 1 parent 362c401
@jnunemaker authored
Showing with 27 additions and 9 deletions.
  1. +0 −4 README.rdoc
  2. +9 −4 lib/bin/store.rb
  3. +18 −1 spec/bin/store_spec.rb
View
4 README.rdoc
@@ -2,10 +2,6 @@
ActiveSupport MongoDB Cache store.
-== Notes
-
-* Only tested with strings. Need to add object marshaling.
-
== Supports
* Ruby 1.8.7 and Ruby 1.9.1.
View
13 lib/bin/store.rb
@@ -11,10 +11,12 @@ def expires_in
@expires_in ||= options[:expires_in] || 1.year
end
- def write(key, value, options=nil)
+ def write(key, value, options={})
super do
expires = Time.now.utc + ((options && options[:expires_in]) || expires_in)
- doc = {:_id => key, :value => value, :expires_at => expires}
+ raw = !!options[:raw]
+ value = raw ? value : Marshal.dump(value)
+ doc = {:_id => key, :value => value, :expires_at => expires, :raw => raw}
collection.save(doc)
end
end
@@ -22,7 +24,7 @@ def write(key, value, options=nil)
def read(key, options=nil)
super do
if doc = collection.find_one(:_id => key, :expires_at => {'$gt' => Time.now.utc})
- doc['value']
+ doc['raw'] ? doc['value'] : Marshal.load(doc['value'])
end
end
end
@@ -70,7 +72,10 @@ def counter_key_upsert(key, amount)
collection.update(
{:_id => key}, {
'$inc' => {:value => amount},
- '$set' => {:expires_at => Time.now.utc + 1.year},
+ '$set' => {
+ :expires_at => Time.now.utc + 1.year,
+ :raw => true
+ },
}, :upsert => true)
end
end
View
19 spec/bin/store_spec.rb
@@ -37,7 +37,18 @@
end
it "sets value key to value" do
+ store.read('foo').should == 'bar'
+ end
+
+ it "should marshal value by default" do
+ document['value'].should == Marshal.dump('bar')
+ document['raw'].should be_false
+ end
+
+ it "should be able to store in raw format" do
+ store.write('foo', 'bar', :raw => true)
document['value'].should == 'bar'
+ document['raw'].should be_true
end
it "sets expires in to default if not provided" do
@@ -54,12 +65,18 @@
before(:each) do
store.write('foo', 'bar')
end
+ let(:document) { collection.find_one(:_id => 'foo') }
it "returns nil for key not found" do
store.read('non:existent:key').should be_nil
end
- it "returns value key value for key found" do
+ it "returns unmarshalled value key value for key found" do
+ store.read('foo').should == 'bar'
+ end
+
+ it "returns raw value if document raw key is true" do
+ store.write('foo', 'bar', :raw => true)
store.read('foo').should == 'bar'
end
Please sign in to comment.
Something went wrong with that request. Please try again.