Class: Mathjax_Renderer::Renderer

Inherits:
Object
  • Object
show all
Includes:
Capybara::DSL
Defined in:
lib/mathjax_renderer/renderer.rb

Instance Method Summary collapse

Constructor Details

#initialize(mathml, image_base_url = nil, options = {}) ⇒ Renderer

Returns a new instance of Renderer.



9
10
11
12
13
# File 'lib/mathjax_renderer/renderer.rb', line 9

def initialize(mathml, image_base_url = nil, options = {})
  @mathml = mathml
  @image_base_url = image_base_url
  @options = {min_width: 0, extra_style:'', padding:0}.merge options
end

Instance Method Details

#htmlObject



80
81
82
83
84
85
86
# File 'lib/mathjax_renderer/renderer.rb', line 80

def html
  return cached(params_hash) if cached? params_hash

  render! if @html.nil?

  @html
end

#image_nameObject

Raises:

  • (ArgumentError)


15
16
17
18
19
# File 'lib/mathjax_renderer/renderer.rb', line 15

def image_name
  raise ArgumentError if @image_base_url.nil?
  render! unless File.exist?(image_path)
  _image_name
end

#render!Object



21
22
23
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
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/mathjax_renderer/renderer.rb', line 21

def render!
  server = RendererServer.new
  server.ensure_started!

  added_margin = [@options[:padding],@options[:min_width]].max

  url = server.add_content(@mathml, added_margin, @options[:extra_style])

  Headless.ly do

    Capybara.register_driver :chrome do |app|
      Capybara::Selenium::Driver.new(app, :browser => :chrome)
    end

    Capybara.default_driver = :chrome
    Capybara.app_host = "http://localhost:#{server.port}"

    visit url

    def mathjax_ready?(page)
      html = Nokogiri::HTML(page.html)
      !html.css('.MathJax').empty? && html.css('.MathJax_Processing').empty? && html.css('.MathJax_Processed').empty?
    end

    sleep 0.1 until mathjax_ready?(page)

    unless @image_base_url.nil?
      require 'chunky_png'
      driver = page.driver

      require 'fileutils'
      FileUtils.mkpath @image_base_url

      driver.save_screenshot(image_path)

      el= page.find('.MathJax .math').native

      image = ChunkyPNG::Image.from_file(image_path)

      correction = [(@options[:min_width] -(el.size.width + 2 * @options[:padding])) / 2,0].max

      x = el.location.x + 1 - @options[:padding]-correction
      y = el.location.y + 1 - @options[:padding]
      width = [el.size.width + 2 * @options[:padding],@options[:min_width]].max
      height = el.size.height+ 2 * @options[:padding]

      image.crop!(x, y, width, height)
      image.save(image_path)
    end
    result = Nokogiri::HTML(page.html).css('.MathJax')[0]

    put_cache!(params_hash,result)

    page.driver.quit

    @html = result
  end
end