Added XPath::Compiler.compile_with_cache

This commit is contained in:
Yorick Peterse 2015-07-08 00:56:05 +02:00
parent 6d01adafc7
commit 3300a6df49
2 changed files with 38 additions and 4 deletions

View File

@ -9,9 +9,21 @@ module Oga
# recompiling the same expression over and over again. # recompiling the same expression over and over again.
# #
class Compiler class Compiler
# @return [Oga::LRU]
CACHE = LRU.new
# Wildcard for node names/namespace prefixes. # Wildcard for node names/namespace prefixes.
STAR = '*' STAR = '*'
##
# Compiles and caches an AST.
#
# @see [#compile]
#
def self.compile_with_cache(ast)
CACHE.get_or_set(ast) { new.compile(ast) }
end
## ##
# Compiles an XPath AST into a Ruby Proc. # Compiles an XPath AST into a Ruby Proc.
# #

View File

@ -5,6 +5,32 @@ describe Oga::XPath::Compiler do
@compiler = described_class.new @compiler = described_class.new
end end
describe 'compile_with_cache' do
before do
described_class::CACHE.clear
end
it 'returns a Proc as a lambda' do
ast = parse_xpath('foo')
block = described_class.compile_with_cache(ast)
block.should be_an_instance_of(Proc)
block.lambda?.should == true
end
it 'caches a compiled Proc' do
ast = parse_xpath('foo')
described_class.any_instance
.should_receive(:compile)
.once
.and_call_original
described_class.compile_with_cache(ast).should be_an_instance_of(Proc)
described_class.compile_with_cache(ast).should be_an_instance_of(Proc)
end
end
describe '#compile' do describe '#compile' do
it 'returns a Proc as a lambda' do it 'returns a Proc as a lambda' do
ast = parse_xpath('foo') ast = parse_xpath('foo')
@ -21,10 +47,6 @@ describe Oga::XPath::Compiler do
@compiler.compile(ast).arity.should == 1 @compiler.compile(ast).arity.should == 1
end end
xit 'caches a compiled Proc for a given XPath AST' do
# TODO
end
describe 'calling the compiled Proc' do describe 'calling the compiled Proc' do
it 'returns a NodeSet' do it 'returns a NodeSet' do
doc = parse('<foo></foo>') doc = parse('<foo></foo>')