LoginSignup
9
7

More than 5 years have passed since last update.

Railsのi18nのyamlにRubyの変数を使えるようにする

Last updated at Posted at 2015-05-29

I18nで使われるt(translate)関数をoverrideする

ApplicationControllerに下記を追加する

app/controllers/application_controller.rb
  # 辞書ファイル(.ymlファイル)の中でrubyコードを使えるようにする
  #
  #   ** I18nのtransate(t)メソッドをオーバライド **
  #
  def I18n.t(code, options = {})

    begin
      message_code = code
      normal_translated = super message_code, options
      translated = eval("\"#{normal_translated}\"")
      return translated
    rescue SyntaxError => ex
      return normal_translated
    end

  end

これでlocaleのymlファイルにruby変数を使用することができるようになります。

rails_configなどのGemを使って、

アプリケーション名を

Settings.app_name

で取得できるようにしておいた時、

config/locales/devise.ja.yml
ja:
  devise:
    mailer:
      confirmation_instructions:
        subject: "【#{Settings.app_name}】アカウントの登録のご案内"
      reset_password_instructions:
        subject: "【#{Settings.app_name}】パスワードの再設定のご案内"
      unlock_instructions:
        subject: '【#{Settings.app_name}】アカウントのロック解除のご案内'

としておけば、Deviseがユーザ登録などの時に送る、
メールの件名に、設定したアプリケーション名を表示させることが出来ます。

結局、作成したApplicationController全体では下記のようになります。

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception


  # 辞書ファイル(.ymlファイル)の中でrubyコードを使えるようにする
  #
  #   ** I18nのtransate(t)メソッドをオーバライド **
  #
  def I18n.t(code, options = {})

    begin
      message_code = code
      normal_translated = super message_code, options
      translated = eval("\"#{normal_translated}\"")
      return translated
    rescue SyntaxError => ex
      return normal_translated
    end

  end


end

※参考URL
http://tech.aktsk.jp/%E6%8A%80%E8%A1%93/ruby-%E6%8A%80%E8%A1%93/20111223/266

9
7
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
9
7