Permalink
Browse files

Changed semantics of fetch to work more like ruby hash fetch.

Does not write the block result to the key if key not found. Instead, now it allows you to write the key in the block if you want and it will do another read to check or you can just return result of block.
  • Loading branch information...
jnunemaker committed Jan 27, 2011
1 parent 99d261f commit b7c074859c4fb2bd74662d01063f7e534cf7bfc5
Showing with 15 additions and 7 deletions.
  1. +2 −3 lib/adapter/defaults.rb
  2. +13 −4 spec/adapter_spec.rb
View
@@ -2,9 +2,8 @@ module Adapter
module Defaults
def fetch(key, value=nil, &block)
read(key) || begin
- value = yield(key) if value.nil? && block_given?
- write(key, value)
- value
+ value = block_given? ? yield(key) : value
+ read(key) || value
end
end
View
@@ -195,12 +195,12 @@ def decode(value)
end
describe "#fetch" do
- it "returns value if found" do
+ it "returns value if key found" do
adapter.write('foo', 'bar')
adapter.fetch('foo', 'baz').should == 'bar'
end
- it "returns value if not found" do
+ it "returns default value if not key found" do
adapter.fetch('foo', 'baz').should == 'baz'
end
@@ -213,11 +213,20 @@ def decode(value)
end.should == 'bar'
end
- it "returns result of block if key not found and writes result to key" do
+ it "returns default if key not found" do
+ adapter.fetch('foo', 'default').should == 'default'
+ end
+
+ it "returns result of block if key not found" do
adapter.fetch('foo') do
'baz'
end.should == 'baz'
- adapter.fetch('foo').should == 'baz'
+ end
+
+ it "returns key if result of block writes key" do
+ adapter.fetch('foo', 'default') do
+ adapter.write('foo', 'write in block')
+ end.should == 'write in block'
end
it "yields key to block" do

0 comments on commit b7c0748

Please sign in to comment.