054df415f9
Nokogiri produces inefficient XPath expressions when given CSS expressions such as "a.gfm". Luckily these expressions can be optimized quite easily while still achieving the same results. In the two cases where this optimization is applied the run time has been reduced from around 170 ms to around 15 ms.
18 lines
582 B
Ruby
18 lines
582 B
Ruby
module Banzai
|
|
module Querying
|
|
# Searches a Nokogiri document using a CSS query, optionally optimizing it
|
|
# whenever possible.
|
|
#
|
|
# document - A document/element to search.
|
|
# query - The CSS query to use.
|
|
#
|
|
# Returns a Nokogiri::XML::NodeSet.
|
|
def self.css(document, query)
|
|
# When using "a.foo" Nokogiri compiles this to "//a[...]" but
|
|
# "descendant::a[...]" is quite a bit faster and achieves the same result.
|
|
xpath = Nokogiri::CSS.xpath_for(query)[0].gsub(%r{^//}, 'descendant::')
|
|
|
|
document.xpath(xpath)
|
|
end
|
|
end
|
|
end
|