Skip to content

Commit

Permalink
Call ERB.new correctly depending on the RUBY_VERSION
Browse files Browse the repository at this point in the history
* On Ruby 3.0.x and older, call ERB.new(template_code, nil, "-")
* On Ruby 3.1.0 and newer, call ERB.new(template_code, trim_mode: "-")

Fixes #1894
  • Loading branch information
jordansissel committed May 2, 2022
1 parent 5d2b485 commit 7881705
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
5 changes: 3 additions & 2 deletions lib/fpm/package.rb
Expand Up @@ -331,11 +331,12 @@ def template(path)
template_path = File.join(template_dir, path)
template_code = File.read(template_path)
logger.info("Reading template", :path => template_path)
erb = ERB.new(template_code, nil, "-")
erb = erbnew(template_code)
erb.filename = template_path
return erb
end # def template


#######################################
# The following methods are provided to
# easily override particular substitut-
Expand Down Expand Up @@ -518,7 +519,7 @@ def write_scripts
# flag), then apply it as an ERB template.
def script(script_name)
if attributes[:template_scripts?]
erb = ERB.new(scripts[script_name], nil, "-")
erb = erbnew(scripts[script_name])
# TODO(sissel): find the original file name for the file.
erb.filename = "script(#{script_name})"
return erb.result(binding)
Expand Down
23 changes: 23 additions & 0 deletions lib/fpm/util.rb
Expand Up @@ -406,6 +406,29 @@ def expand_pessimistic_constraints(constraint)
def logger
@logger ||= Cabin::Channel.get
end # def logger

def erbnew(template_code)
# In Ruby 2.6(?), Ruby changed how ERB::new is invoked.
# First, it added keyword args like `ERB.new(..., trim_mode: "-")`
# Later, it deprecated then removed the safe_level feature.
# As of Ruby 3.1, warnings are printed at runtime when ERB.new is called with the old syntax.
# Ruby 2.5 and older does not support the ERB.new keyword args.
#
# My tests showed:
# * Ruby 2.3.0 through 3.0 work correctly with the old syntax.
# * Ruby 3.1.0 and newer (at time of writing, Ruby 3.2) require the new syntax
# Therefore, in order to support the most versions of ruby, we need to do a version check
# to invoke ERB.new correctly and without printed warnings.
# References: https://github.com/jordansissel/fpm/issues/1894
# Honestly, I'm not sure if Gem::Version is correct to use in this situation, but it works.
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new("3.1.0")
# Ruby 3.0.x and older
return ERB.new(template_code, nil, "-")
else
# Ruby 3.1.0 and newer
return ERB.new(template_code, trim_mode: "-")
end
end
end # module FPM::Util

require 'fpm/util/tar_writer'

0 comments on commit 7881705

Please sign in to comment.