Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

fix cache class interface

  • Loading branch information...
commit 74bfbfdb028bf4fb97fdf93451caeb49aa89ff39 1 parent a924e0d
@tenderlove tenderlove authored
View
22 activerecord/lib/active_record/statement_cache.rb
@@ -14,13 +14,25 @@ module ActiveRecord
# The relation returned by the block is cached, and for each +execute+ call the cached relation gets duped.
# Database is queried when +to_a+ is called on the relation.
class StatementCache
- def initialize
- @relation = yield
- raise ArgumentError.new("Statement cannot be nil") if @relation.nil?
+ def initialize(block = Proc.new)
+ @mutex = Mutex.new
+ @relation = nil
+ @block = block
end
- def execute
- @relation.dup.to_a
+ def execute(*vals)
+ rel = relation vals
+ @mutex.synchronize do
+ rel.set_binds vals
+ rel.to_a
+ end
+ end
+
+ private
+ def relation(values)
+ @relation || @mutex.synchronize {
+ @block.call(*values)
+ }
end
end
end
View
26 activerecord/test/cases/statement_cache_test.rb
@@ -15,13 +15,13 @@ def test_statement_cache
Book.create(name: "my book")
Book.create(name: "my other book")
- cache = StatementCache.new do
- Book.where(:name => "my book")
+ cache = StatementCache.new do |name|
+ Book.where(:name => name)
end
- b = cache.execute name: "my book"
+ b = cache.execute "my book"
assert_equal "my book", b[0].name
- b = cache.execute name: "my other book"
+ b = cache.execute "my other book"
assert_equal "my other book", b[0].name
end
@@ -31,13 +31,13 @@ def test_statement_cache_id
Book.create(name: "my book")
Book.create(name: "my other book")
- cache = StatementCache.new do
- Book.where(id: "1")
+ cache = StatementCache.new do |id|
+ Book.where(id: id)
end
- b = cache.execute id: "1"
+ b = cache.execute "1"
assert_equal "my book", b[0].name
- b = cache.execute id: "2"
+ b = cache.execute "2"
assert_equal "my other book", b[0].name
end
@@ -64,14 +64,6 @@ def test_statement_cache_with_simple_statement
assert_equal "my book", books[0].name
end
- def test_statement_cache_with_nil_statement_raises_error
- assert_raise(ArgumentError) do
- ActiveRecord::StatementCache.new do
- nil
- end
- end
- end
-
def test_statement_cache_with_complex_statement
cache = ActiveRecord::StatementCache.new do
Liquid.joins(:molecules => :electrons).where('molecules.name' => 'dioxane', 'electrons.name' => 'lepton')
@@ -104,4 +96,4 @@ def test_statement_cache_values_differ
assert first_books != additional_books
end
end
-end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.