Class: Mjml::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/mjml/parser.rb

Defined Under Namespace

Classes: ParseError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ Parser

Create new parser

Parameters:

  • input (String)

    The string to transform in html



12
13
14
15
# File 'lib/mjml/parser.rb', line 12

def initialize input
  raise Mjml.mjml_binary_error_string unless mjml_bin
  @input = input
end

Instance Attribute Details

#inputObject (readonly)

Returns the value of attribute input.



7
8
9
# File 'lib/mjml/parser.rb', line 7

def input
  @input
end

Instance Method Details

#renderString

Render mjml template

Returns:

  • (String)


20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/mjml/parser.rb', line 20

def render
  in_tmp_file = Tempfile.open(["in", ".mjml"]) do |file|
    file.write(input)
    file # return tempfile from block so #unlink works later
  end
  run(in_tmp_file.path, Mjml.beautify, Mjml.minify)
rescue
  raise if Mjml.raise_render_exception
  ""
ensure
  in_tmp_file.unlink
end

#run(in_tmp_file, beautify = true, minify = false) ⇒ String

Exec mjml command

Returns:

  • (String)

    The result as string



36
37
38
39
40
41
42
43
# File 'lib/mjml/parser.rb', line 36

def run(in_tmp_file, beautify=true, minify=false)
  Tempfile.create(["out", ".html"]) do |out_tmp_file|
    command = "#{mjml_bin} -r #{in_tmp_file} -o #{out_tmp_file.path} --config.beautify #{beautify} --config.minify #{minify}"
    _, _, stderr, _ = Open3.popen3(command)
    raise ParseError.new(stderr.read.chomp) unless stderr.eof?
    out_tmp_file.read
  end
end