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(template_path, input) ⇒ Parser

Create new parser

Parameters:

  • template_path (String)

    The path to the .mjml file

  • input (String)

    The content of the .mjml file



16
17
18
19
20
21
22
# File 'lib/mjml/parser.rb', line 16

def initialize(template_path, input)
  raise Mjml.mjml_binary_error_string unless Mjml.valid_mjml_binary

  @template_path = template_path
  @input         = input
  @with_cache    = Cache.new(template_path)
end

Instance Attribute Details

#inputObject (readonly)

Returns the value of attribute input.



10
11
12
# File 'lib/mjml/parser.rb', line 10

def input
  @input
end

#template_pathObject (readonly)

Returns the value of attribute template_path.



10
11
12
# File 'lib/mjml/parser.rb', line 10

def template_path
  @template_path
end

Instance Method Details

#build_command(in_file, out_file) ⇒ String

Build command string from config variables

Returns:

  • (String)

    Command string



66
67
68
69
70
71
72
73
# File 'lib/mjml/parser.rb', line 66

def build_command(in_file, out_file)
  command = "-r #{in_file} -o #{out_file.path} " \
            "--config.beautify #{Mjml.beautify} " \
            "--config.minify #{Mjml.minify} " \
            "--config.validationLevel #{Mjml.validation_level}"
  command += " --config.fonts '#{Mjml.fonts.to_json}'" unless Mjml.fonts.nil?
  command
end

#renderString

rubocop:disable Metrics/MethodLength Render MJML template

Returns:

  • (String)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/mjml/parser.rb', line 28

def render
  @with_cache.cache do
    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)
  rescue StandardError
    raise if Mjml.raise_render_exception

    ''
  ensure
    in_tmp_file&.unlink
  end
end

#run(in_tmp_file) ⇒ String

Exec mjml command

Returns:

  • (String)

    The result as string



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/mjml/parser.rb', line 48

def run(in_tmp_file)
  Tempfile.create(['out', '.html']) do |out_tmp_file|
    _, stderr, status = Mjml.run_mjml(build_command(in_tmp_file, out_tmp_file))

    unless status.success?
      # The process status ist quite helpful in case of dying processes without STDERR output.
      # Node exit codes are documented here: https://node.readthedocs.io/en/latest/api/process/#exit-codes
      raise ParseError, "#{stderr.chomp}\n(process status: #{status})"
    end

    Mjml.logger.warn(stderr.chomp) if stderr.present?
    out_tmp_file.read
  end
end