Automatically reload rails yml files in config/locales

Viewed 8157

In rails, the yml files in config/locales allow you to give locale-specific text and formatting directives. For example, you can specify date formatting like this:

# config/locales/en.yml
  date: 
    formats:
      month: "%B, %Y"

Then in your views you can use the helper, like this:

<%= l(Date.today, format: :month) %> => "December, 2013"

Annoyingly, rails only loads the locale files when you start your server, so you have to restart your development server if you want to make a change. Is it possible to automatically reload this on file changes?

3 Answers

I18n detects changes made to existing files in its load path, but if you want to detect new files under locales and add them to the load path at runtime, try this.

# config/initializers/i18n_load_path.rb
if Rails.env.development? || Rails.env.test?
  locales_path = Rails.root.join("config/locales").to_s
  i18n_reloader = ActiveSupport::FileUpdateChecker.new([], locales_path => "yml") do
    Dir["#{locales_path}/*.yml"].each do |locale_path|
      I18n.load_path << locale_path unless I18n.load_path.include? path
    end
  end

  ActiveSupport::Reloader.to_prepare do
    i18n_reloader.execute_if_updated
  end
end

That will monitor the locales directory (or any other directory you want to store locales) and add missing ones to the load path when they are added. I18n picks up on these added files so no need to call reload!.

Related