Class: Mathematical::Render

Inherits:
Object
  • Object
show all
Includes:
Corrections
Defined in:
lib/mathematical/render.rb

Constant Summary collapse

FORMAT_TYPES =
%w(svg png mathml)
DEFAULT_OPTS =
{
  :ppi => 72.0,
  :zoom => 1.0,
  :base64 => false,
  :maxsize => 0,
  :format => "svg"
}

Instance Method Summary collapse

Methods included from Corrections

#adjust_lt_gt, #apply_corrections

Constructor Details

#initialize(opts = {}) ⇒ Render

Returns a new instance of Render.

Raises:

  • (TypeError)


19
20
21
22
23
24
25
26
27
28
# File 'lib/mathematical/render.rb', line 19

def initialize(opts = {})
  @config = DEFAULT_OPTS.merge(opts)

  raise(TypeError, "maxsize must be an integer!") unless @config[:maxsize].is_a? Fixnum
  raise(TypeError, "maxsize cannot be less than 0!") if @config[:maxsize] < 0
  raise(TypeError, "format must be a string!") unless @config[:format].is_a? String
  raise(TypeError, "format type must be one of the following formats: #{FORMAT_TYPES.join(', ')}") unless FORMAT_TYPES.include?(@config[:format])

  @processer = Mathematical::Process.new(@config)
end

Instance Method Details

#render(maths) ⇒ Object

Raises:

  • (TypeError)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/mathematical/render.rb', line 30

def render(maths)
  raise(TypeError, "text must be a string!") unless maths.is_a? String
  maths = maths.strip
  raise(ArgumentError, "text must be in itex format (`$...$` or `$$...$$`)!") unless maths =~ /\A\${1,2}/

  maths = apply_corrections(maths)

  begin
    raise RuntimeError unless data_hash = @processer.process(maths)
    case @config[:format]
    when "svg"
      data_hash["svg"] = data_hash["svg"][xml_header.length..-1] # remove starting <?xml...> tag
      data_hash["svg"] = svg_to_base64(data_hash["svg"]) if @config[:base64]
      data_hash
    when "png", "mathml"
      data_hash
    end
  rescue ParseError, DocumentCreationError, DocumentReadError => e # an error in the C code, probably a bad TeX parse
    $stderr.puts "#{e.message}: #{maths}"
    maths
  end
end