Skip to content

Instantly share code, notes, and snippets.

@bensheldon
Created June 3, 2025 23:05
Show Gist options
  • Save bensheldon/62428f2b3c1708e9947205d3885e9650 to your computer and use it in GitHub Desktop.
Save bensheldon/62428f2b3c1708e9947205d3885e9650 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# Reduce the amount of quote churn in the YAML files that results from
# i18n-tasks attempting to normalize the quotes itself.
# Always attempt to preserve the pre-existing quote style.
require 'psych'
class I18nTasksWrapper
def self.i18n_files
locales_path = File.expand_path('./locales', File.dirname(__FILE__))
Dir[File.join(locales_path, '**/*.yml')]
end
def self.add_placeholders
i18n_files.each do |path|
stream = Psych.parse_stream(File.read(path))
stream.each do |node|
case node
when Psych::Nodes::Mapping
node.children.each_slice(2) { |_, v| add_placeholder(v) }
when Psych::Nodes::Sequence
node.children.each { |value| add_placeholder(value) }
end
end
File.write(path, stream.to_yaml(nil, line_width: -1)) # unlimited line length
end
end
def self.add_placeholder(node)
if node.is_a?(Psych::Nodes::Scalar)
if node.style == Psych::Nodes::Scalar::SINGLE_QUOTED
node.value = "::HACK_PLACEHOLDER#{node.value}"
elsif node.style == Psych::Nodes::Scalar::DOUBLE_QUOTED
node.value = "\tHACK_PLACEHOLDER#{node.value}"
end
end
end
def self.remove_placeholders
i18n_files.each do |path|
File.write(path, File.read(path).gsub(/..HACK_PLACEHOLDER/, ''))
end
end
end
# Add the placeholders when this file loads and remove them when the
# process exits.
I18nTasksWrapper.add_placeholders
at_exit { I18nTasksWrapper.remove_placeholders }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment