LoginSignup
1
1

More than 5 years have passed since last update.

Controller内のI18nで継承を含めてkeyを参照させる

Posted at

ControllerでI18n使う所なんてフラッシュメッセージ位だし
あえて継承気にするまでもないって事な気もするけど、
管理画面とか基本同じメッセージなのにコントローラー毎にyml定義するの面倒くさい!
という気持ちからガッっと書いた。

app/controllers/application_controller.rb
def translate(key, options = {})
  if key.to_s.first == "."
    defaults = _prefixes.map do |prefix|
      path = prefix.tr('/', '.')
      [:"#{path}.#{action_name}#{key}", :"#{path}#{key}"]
    end
    defaults << options[:default] if options[:default]
    options[:default] = defaults.flatten
    options[:scope] = :controller
    key = options[:default].shift
  end
  I18n.translate(key, options)
end
alias :t :translate

これで、例えばこんなキーを読み出す時に

app/controllers/admin/application_controller.rb
class Admin::ApplicationController < ApplicationController
end
app/controllers/admin/users_controller.rb
class Admin::UsersController < Admin::ApplicationController
  def update
    if @user.update(user_params)
      redirect_to [:admin, @user], notice: t('.success')
    else
      render :edit
    end
  end
end
ja:
  controller:
    application:
      success: 6th
      update:
        success: 5th
    admin:
      application:
        success: 4th
        update:
          success: 3rd
      users:
        success: 2nd
        update:
          success: 1st

こんな感じの順番で参照してくれるようになる。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1