Class: Mathematical::Render
- Inherits:
-
Object
- Object
- Mathematical::Render
- Defined in:
- lib/mathematical/render.rb
Constant Summary collapse
- DEFAULT_OPTS =
{ :ppi => 72.0, :zoom => 1.0 }
Instance Method Summary collapse
-
#initialize(opts = {}) ⇒ Render
constructor
A new instance of Render.
- #named_type(type) ⇒ Object
- #render(text) ⇒ Object
- #svg_to_base64(contents) ⇒ Object
Constructor Details
#initialize(opts = {}) ⇒ Render
Returns a new instance of Render.
12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/mathematical/render.rb', line 12 def initialize(opts = {}) raise(TypeError, "opts must be a hash!") unless opts.is_a? Hash @config = DEFAULT_OPTS.merge(opts) begin @processer = Mathematical::Process.new(@config) rescue TypeError => e # some error in the C code raise end end |
Instance Method Details
#named_type(type) ⇒ Object
71 72 73 |
# File 'lib/mathematical/render.rb', line 71 def named_type(type) "#{type.to_s}-math" end |
#render(text) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/mathematical/render.rb', line 24 def render(text) raise(TypeError, "text must be a string!") unless text.is_a? String # TODO: figure out how to write svgs without the tempfile tempfile = Tempfile.new('foo') text.gsub(Mathematical::Parser::REGEX) do |maths| if maths =~ /^\$(?!\$)/ just_maths = maths[1..-2] type = :inline elsif maths =~ /^\\\((?!\\\[)/ just_maths = maths[2..-4] type = :inline elsif maths =~ /^\\\[(?!\\\[)/ just_maths = maths[2..-4] type = :display elsif maths =~ /^\\begin(?!\\begin)/ just_maths = maths[16..-15] type = :display end # this is the format itex2MML expects if type == :inline just_maths = "$#{just_maths}$" else just_maths = "$$#{just_maths}$$" end begin status = @processer.process(just_maths, tempfile.path) raise RuntimeError unless status == 0 svg_content = File.open(tempfile.path, 'r') { |image_file| image_file.read } svg_content = svg_content.lines.to_a[1..-1].join rescue RuntimeError => e # an error in the C code, probably a bad TeX parse $stderr.puts e. return just_maths end "<img class=\"#{named_type(type)}\" data-math-type=\"#{named_type(type)}\" src=\"data:image/svg+xml;base64,#{svg_to_base64(svg_content)}\"/>" end tempfile.close tempfile.unlink end |
#svg_to_base64(contents) ⇒ Object
67 68 69 |
# File 'lib/mathematical/render.rb', line 67 def svg_to_base64(contents) Base64.strict_encode64(contents) end |