Efficiency improvements to itex endpoint

Benchmarks at up to twice as fast.
This commit is contained in:
Jacques Distler 2010-03-01 21:10:13 -06:00
parent a6bceb2a8e
commit e07960a897

View file

@ -14,6 +14,9 @@ class Itex
private private
ESTART = "<math xmlns='http://www.w3.org/1998/Math/MathML' display='inline'><merror><mtext>"
EEND = "</mtext></merror></math>"
# plugable XML parser; falls back to REXML # plugable XML parser; falls back to REXML
begin begin
require 'nokogiri' require 'nokogiri'
@ -26,37 +29,43 @@ class Itex
REXML::Document.new(text) REXML::Document.new(text)
end end
end end
# itex2MML parser
begin
require 'itextomml'
def self.parse_itex(tex, filter)
Itex2MML::Parser.new.send(filter, tex).to_utf8
end
rescue LoadError
def self.parse_itex(tex, filter)
ESTART + "Please install the itex2MML Ruby bindings." + EEND
end
end
def self.response(env) def self.response(env)
@params = Rack::Request.new(env).params params = Rack::Request.new(env).params
tex = (@params['tex'] || '').purify tex = (params['tex'] || '').purify.strip
case @params['display'] case params['display']
when 'block' when 'block'
filter = :block_filter filter = :block_filter
else else
filter = :inline_filter filter = :inline_filter
end end
return "<math xmlns='http://www.w3.org/1998/Math/MathML' display='" + return "<math xmlns='http://www.w3.org/1998/Math/MathML' display='" +
filter.to_s[/(.*?)_filter/] + "'/>" if tex.strip == '' filter.to_s[/(.*?)_filter/] + "'/>" if tex == ''
estart = "<math xmlns='http://www.w3.org/1998/Math/MathML' display='inline'><merror><mtext>"
eend = "</mtext></merror></math>"
begin begin
require 'itextomml' doc = parse_itex(tex, filter)
@itex2mml_parser ||= Itex2MML::Parser.new
doc = @itex2mml_parser.send(filter, tex).to_utf8
# make sure the result is well-formed, before sending it off # make sure the result is well-formed, before sending it off
begin begin
xmlparse(doc) xmlparse(doc)
rescue rescue
return estart +"Ill-formed XML." + eend return ESTART +"Ill-formed XML." + EEND
end end
return doc return doc
rescue LoadError
estart + "Please install the itex2MML Ruby bindings." + eend
rescue Itex2MML::Error => e rescue Itex2MML::Error => e
estart + e.to_s + eend ESTART + e.to_s + EEND
rescue rescue
estart + "Unknown Error" + eend ESTART + "Unknown Error" + EEND
end end
end end
end end