Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically reload rails yml files in config/locales

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?

like image 985
spike Avatar asked Dec 12 '13 22:12

spike


3 Answers

I think Rails misses new translation files, but adding translations to an existing file should work.

Try force reload it with I18n.backend.reload!

I hope this helps ;)

like image 176
danilodeveloper Avatar answered Nov 02 '22 18:11

danilodeveloper


There's attempted support for this in rails 3.2:

https://github.com/rails/rails/blob/v3.2.16/activesupport/lib/active_support/i18n_railtie.rb

However, it comes with this disclaimer:

# Add <tt>I18n::Railtie.reloader</tt> to ActionDispatch callbacks. Since, at this
# point, no path was added to the reloader, I18n.reload! is not triggered
# on to_prepare callbacks. This will only happen on the config.after_initialize
# callback below.

There's some better looking code in rails 4, so this problem might be fixed there (I don't use rails 4 yet).

I added the following initializer, which checks for changed files is config/locales and reloads I18n:

# config/initializers/reload_locale.rb
if Rails.env == 'development'
  locale_reloader = ActiveSupport::FileUpdateChecker.new(Dir["config/locales/*yml"]) do
     I18n.backend.reload!
  end

  ActionDispatch::Callbacks.to_prepare do
    locale_reloader.execute_if_updated
  end
end
like image 41
spike Avatar answered Nov 02 '22 18:11

spike


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!.

like image 2
ryanb Avatar answered Nov 02 '22 18:11

ryanb