Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away