Created
June 3, 2025 23:05
-
-
Save bensheldon/62428f2b3c1708e9947205d3885e9650 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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