Skip to content

Commit

Permalink
refactor detection of binary and unify executing mjml
Browse files Browse the repository at this point in the history
- detect local first, then global
- use `yarn run` if installed with yarn, makes it work with yarn v2
- only use bin path when installed with npm, yarn should always work
  with `yarn run`
- always execute mjml in the same way, whether when checking version or
  transforming mail
  • Loading branch information
doits committed Nov 18, 2020
1 parent cdaac98 commit 063152c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
28 changes: 18 additions & 10 deletions lib/mjml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,32 @@ module Mjml
@@validation_level = "soft"

def self.check_version(bin)
IO.popen([bin, '--version']) { |io| io.read.include?("mjml-core: #{Mjml.mjml_binary_version_supported}") }
rescue
stdout, _, status = run_mjml('--version', mjml_bin: bin)
status.success? && stdout.include?("mjml-core: #{Mjml.mjml_binary_version_supported}")
rescue StandardError
false
end

def self.run_mjml(args, mjml_bin: nil)
mjml_bin ||= BIN

Open3.capture3("#{mjml_bin} #{args}")
end

def self.discover_mjml_bin
# Check for a global install of MJML binary
mjml_bin = 'mjml'
# Check for local install of MJML with yarn
mjml_bin = 'yarn run mjml'
return mjml_bin if check_version(mjml_bin)

# Check for a local install of MJML binary
installer_path = bin_path_from('npm') || bin_path_from('yarn')
unless installer_path
puts Mjml.mjml_binary_error_string
return nil
# Check for a local install of MJML binary with npm
installer_path = bin_path_from('npm')
if installer_path
mjml_bin = File.join(installer_path, 'mjml')
return mjml_bin if check_version(mjml_bin)
end

mjml_bin = File.join(installer_path, 'mjml')
# Check for a global install of MJML binary
mjml_bin = 'mjml'
return mjml_bin if check_version(mjml_bin)

puts Mjml.mjml_binary_error_string
Expand Down
6 changes: 3 additions & 3 deletions lib/mjml/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ def render
# @return [String] The result as string
def run(in_tmp_file, beautify=true, minify=false, validation_level="soft")
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} --config.validationLevel #{validation_level}"
_, _, stderr, _ = Open3.popen3(command)
raise ParseError.new(stderr.read.chomp) unless stderr.eof?
command = "-r #{in_tmp_file} -o #{out_tmp_file.path} --config.beautify #{beautify} --config.minify #{minify} --config.validationLevel #{validation_level}"
_, stderr, status = Mjml.run_mjml(command)
raise ParseError.new(stderr.chomp) unless status.success?
out_tmp_file.read
end
end
Expand Down

0 comments on commit 063152c

Please sign in to comment.