Skip to content

Commit

Permalink
[ruby/yarp] Fix up template reading with LANG=C
Browse files Browse the repository at this point in the history
  • Loading branch information
kddnewton authored and matzbot committed Sep 2, 2023
1 parent cfcb4a4 commit 678112c
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions yarp/templates/template.rb
Expand Up @@ -264,13 +264,8 @@ class << self
def template(name, write_to: nil)
filepath = "templates/#{name}.erb"
template = File.expand_path("../#{filepath}", __dir__)
write_to ||= File.expand_path("../#{name}", __dir__)

if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+
erb = ERB.new(File.read(template), trim_mode: "-")
else
erb = ERB.new(File.read(template), nil, "-")
end
erb = read_template(template)
erb.filename = template

non_ruby_heading = <<~HEADING
Expand Down Expand Up @@ -299,13 +294,34 @@ def template(name, write_to: nil)
non_ruby_heading
end

write_to ||= File.expand_path("../#{name}", __dir__)
contents = heading + erb.result_with_hash(locals)

FileUtils.mkdir_p(File.dirname(write_to))
File.write(write_to, contents)
end

private

def read_template(filepath)
previous_verbosity = $VERBOSE
previous_default_external = Encoding.default_external
$VERBOSE = nil

begin
Encoding.default_external = Encoding::UTF_8

if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+
ERB.new(File.read(filepath), trim_mode: "-")
else
ERB.new(File.read(filepath), nil, "-")
end
ensure
Encoding.default_external = previous_default_external
$VERBOSE = previous_verbosity
end
end

def locals
@locals ||=
begin
Expand Down Expand Up @@ -340,7 +356,6 @@ def locals
if ARGV.empty?
YARP::TEMPLATES.each { |filepath| YARP.template(filepath) }
else # ruby/ruby
Encoding.default_external = Encoding::UTF_8
name, write_to = ARGV
YARP.template(name, write_to: write_to)
end
Expand Down

0 comments on commit 678112c

Please sign in to comment.