Skip to content

Instantly share code, notes, and snippets.

@scmx
Created March 15, 2023 13:29
Show Gist options
  • Save scmx/a1b68c7e9206fb62c5e2387c308d04f3 to your computer and use it in GitHub Desktop.
Save scmx/a1b68c7e9206fb62c5e2387c308d04f3 to your computer and use it in GitHub Desktop.
Ruby on Rails compare yaml locales by key for each language #rails #locales #yml #compare #ruby #script

Ruby on Rails compare yaml locales by key for each language

Comparison tool for rails locales.

Pass in dotation paths for interesting yaml parts and this tool will travsere through all locales looking for matches, printing the found value for each locale if a match is found.

Example usage

$ bin/locales-compare thing.fields.type.options.{foo,bar,baz}.{label,help}

thing.fields.thing_type.options.foo.label
dk  "Ståldør"
en  "Pedestrain Door"
nb  "Ståldør"
sv  "Ståldörr"

thing.fields.thing_type.options.foo.help
dk  "Bredde"
en  "Width"
nb  "Bredde"
sv  "Bredd"

thing.fields.thing_type.options.bar.label
dk  "Svingport"
en  "Framed Hinged Door"
nb  "Slagport"
sv  "Slagport"
...

bin/locales-compare

#!/usr/bin/env ruby

require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
  Pathname.new(__FILE__).realpath)

require "rubygems"
require "bundler/setup"
require "colorize"
require "yaml"
require "pp"

all_locales = {}

Dir["config/locales/**/*.yml"].each do |filename|
  *parts, locale = File.basename(filename).split(".")[0..-2]
  name = parts.join(".")
  all_locales[name] ||= {}
  all_locales[name][locale] =
    YAML.safe_load(File.read(filename), [], [], true)[locale]
end

ARGV.each do |yaml_search_path|
  all_matches = []

  all_locales.each do |_name, locales|
    matches = {}

    locales.each do |locale, yaml|
      next unless yaml
      match = yaml.dig(*yaml_search_path.split("."))
      matches[locale] = match if match
    end

    all_matches << matches
  end

  next if all_matches.empty?

  puts yaml_search_path.red

  all_matches.each do |matches|
    matches.each do |locale, match|
      puts "#{locale.yellow}  #{match.pretty_inspect}".chomp
    end
  end
end

If you don't want to add colorize as a dependency then you could implement String#red like this and avoid loading bundler etc:

class String
  def colorize(color_code)
    "\e[#{color_code}m#{self}\e[0m"
  end

  def red
    colorize(31)
  end

  def green
    colorize(32)
  end

  def yellow
    colorize(33)
  end

  def blue
    colorize(34)
  end

  def pink
    colorize(35)
  end

  def light_blue
    colorize(36)
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment