Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Adding TC.open semantics like File.open

  • Loading branch information...
commit 42bc6ac95b5fa5b73aaef0806a01315e6a34be61 1 parent 1c4c392
@zev zev authored
View
2  CHANGELOG.txt
@@ -7,7 +7,7 @@
- todo : aligned Rufus::Tokyo::Table#new on ::Cabinet#new
- todo : added opts (:prefix, :limit, :native) to Rufus::Tokyo::Cabinet#keys,
Rufus::Tokyo::Table#keys and the corresponding Tyrant classes
-
+- add : Rufus::Tokyo::Cabinet has open method that takes a block like File.open
== rufus-tokyo - 0.1.6 released 2009/02/16
View
14 lib/rufus/tokyo/cabinet/abstract.rb
@@ -116,6 +116,20 @@ def initialize (name, params={})
@default_proc ||= params[:default_proc]
end
+ # Same args as initialize, but can take a block form that will
+ # close the db when done. Similar to File.open
+ def self.open (name, params={})
+ db = self.new(name, params)
+ if block_given?
+ yield db
+ nil
+ else
+ db
+ end
+ ensure
+ db.close if block_given? && db
+ end
+
#
# Returns a new in-memory hash. Accepts the same optional params hash
# as new().
View
38 spec/cabinet_spec.rb
@@ -194,5 +194,43 @@
FileUtils.rm('tmp/spec_source.tch')
FileUtils.rm('tmp/spec_target.tch')
end
+
+
+ it 'should use open with a block will auto close the db correctly' do
+
+ res = Rufus::Tokyo::Cabinet.open('tmp/spec_source.tch') do |cab|
+ 10.times { |i| cab["key #{i}"] = "val #{i}" }
+ cab.size.should.equal(10)
+ end
+
+ res.should.be.nil
+
+ cab = Rufus::Tokyo::Cabinet.new('tmp/spec_source.tch')
+ 10.times do |i|
+ cab["key #{i}"].should.equal("val #{i}")
+ end
+ cab.close
+
+ FileUtils.rm('tmp/spec_source.tch')
+ end
+
+
+ it 'should use open without a block just like calling new correctly' do
+
+ cab = Rufus::Tokyo::Cabinet.open('tmp/spec_source.tch')
+ 10.times { |i| cab["key #{i}"] = "val #{i}" }
+ cab.size.should.equal(10)
+ cab.close
+
+ cab = Rufus::Tokyo::Cabinet.new('tmp/spec_source.tch')
+ 10.times do |i|
+ cab["key #{i}"].should.equal("val #{i}")
+ end
+ cab.close
+
+ FileUtils.rm('tmp/spec_source.tch')
+ end
+
+
end

0 comments on commit 42bc6ac

Please sign in to comment.
Something went wrong with that request. Please try again.