mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
fix cache class interface
This commit is contained in:
parent
a924e0dbcd
commit
74bfbfdb02
2 changed files with 26 additions and 22 deletions
|
@ -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
|
||||
|
|
|
@ -15,13 +15,13 @@ module ActiveRecord
|
|||
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 @@ module ActiveRecord
|
|||
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 @@ module ActiveRecord
|
|||
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 @@ module ActiveRecord
|
|||
assert first_books != additional_books
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue