Skip to content

Instantly share code, notes, and snippets.

@hiroshi
Last active November 3, 2016 13:13
Show Gist options
  • Save hiroshi/2e0a27650bf94797f59ec0b0d5c8a8a5 to your computer and use it in GitHub Desktop.
Save hiroshi/2e0a27650bf94797f59ec0b0d5c8a8a5 to your computer and use it in GitHub Desktop.
How to filter keys of i18n-js only used in .js files
  1. Prerequisites

You must use i18n-tasks and make sure i18n-tasks health is OK. I recommend that running i18n-tasks health along with your tests in CI.

  1. Download i18n-tasks_js.rb as lib/i18n_tasks/js.rb in your project.

  2. Insert the line below into the top of config/i18n-tasks.yml

<% require './lib/i18n_tasks/js' %>
  1. You will see the js-keys command is installed.
$ i18n-tasks -h
...
    js-keys                          export i18n keys that used in js
  1. Export js-keys.json
$ i18n-tasks js-keys > tmp/js-keys.json
  1. Include js-keys.json as a only field like this.
translations:
- file: 'public/javascripts/path-to-your-messages-file.js'
  only: <%= File.read('tmp/js-keys.json') %>

Your i18n:js:export process may look like this:

i18n-tasks js-keys > tmp/js-keys.json && rake i18n:js:export
# lib/i18n_tasks/js.rb
module I18nTasks
module Js
include ::I18n::Tasks::Command::Collection
cmd :js_keys, desc: 'export i18n keys that used in js'
def js_keys
keys = []
# keys used in js
i18n.used_tree.nodes do |node|
if node.leaf? && node.data[:occurrences].map(&:path).any? { |path| path =~ /\.js$/ }
keys << node.key
end
end
# keys that match `ignore_unused`
i18n.data.get(:en).nodes do |node|
if i18n.ignore_key?(node.key, :unused)
keys << node.key
end
end
# output result
STDOUT.puts keys.map { |k| "*.#{k}" }.inspect
end
end
end
I18n::Tasks.add_commands I18nTasks::Js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment