Class: Lcms::Engine::EmbedEquations

Inherits:
Object
  • Object
show all
Defined in:
app/services/lcms/engine/embed_equations.rb

Constant Summary collapse

REDIS_KEY =
'ub-equation:'
REDIS_KEY_SVG =
"#{REDIS_KEY}svg:"

Class Method Summary collapse

Class Method Details

.call(content) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'app/services/lcms/engine/embed_equations.rb', line 10

def call(content)
  frag = Nokogiri::HTML.fragment(content)

  frag.css('img').each do |img|
    tex = fetch_tex img[:src]
    html = tex_to_html tex
    next unless (equation_node = Nokogiri::HTML.fragment(html).at_css('span'))

    img.replace(equation_node)
  end

  frag.to_s
end

.tex_to_html(tex) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'app/services/lcms/engine/embed_equations.rb', line 24

def tex_to_html(tex)
  return if tex.blank?

  if (html = redis.get("#{REDIS_KEY}#{tex}")).blank?
    html = `tex2html -- '#{tex}'`
    redis.set "#{REDIS_KEY}#{tex}", html
  end

  html
end

.tex_to_svg(tex, custom_color: nil, preserve_color: false) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/services/lcms/engine/embed_equations.rb', line 35

def tex_to_svg(tex, custom_color: nil, preserve_color: false)
  return if tex.blank?

  key = "#{REDIS_KEY_SVG}#{tex}#{preserve_color}#{custom_color}"
  if (svg = redis.get(key)).blank?
    if custom_color.present?
      tex = "\\require{color}\\definecolor{math}{RGB}{#{custom_color}}\\color{math}{#{tex}}"
    end
    svg = `tex2svg -- '#{tex}'`

    #
    # Should make that change only for Web view.
    # Settings color to `initial` prevents it from customization
    #
    svg = fix_color(svg, preserve_color) unless custom_color.present?

    redis.set key, svg
  end

  svg
end