Class: RuboCop::Cop::Rails::I18nLocaleTexts

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rails/i18n_locale_texts.rb

Overview

Enforces use of I18n and locale files instead of locale specific strings.

Examples:

# bad
class User < ApplicationRecord
  validates :email, presence: { message: "must be present" }
end

# good
# config/locales/en.yml
# en:
#   activerecord:
#     errors:
#       models:
#         user:
#           blank: "must be present"

class User < ApplicationRecord
  validates :email, presence: true
end

# bad
class PostsController < ApplicationController
  def create
    # ...
    redirect_to root_path, notice: "Post created!"
  end
end

# good
# config/locales/en.yml
# en:
#   posts:
#     create:
#       success: "Post created!"

class PostsController < ApplicationController
  def create
    # ...
    redirect_to root_path, notice: t(".success")
  end
end

# bad
class UserMailer < ApplicationMailer
  def welcome(user)
    mail(to: user.email, subject: "Welcome to My Awesome Site")
  end
end

# good
# config/locales/en.yml
# en:
#   user_mailer:
#     welcome:
#       subject: "Welcome to My Awesome Site"

class UserMailer < ApplicationMailer
  def welcome(user)
    mail(to: user.email)
  end
end

Constant Summary collapse

MSG =
'Move locale texts to the locale files in the `config/locales` directory.'
RESTRICT_ON_SEND =
%i[validates redirect_to redirect_back []= mail].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/rubocop/cop/rails/i18n_locale_texts.rb', line 94

def on_send(node)
  case node.method_name
  when :validates
    validation_message(node) do |text_node|
      add_offense(text_node)
    end
    return
  when :redirect_to, :redirect_back
    text_node = redirect_to_flash(node).to_a.last
  when :[]=
    text_node = flash_assignment?(node)
  when :mail
    text_node = mail_subject(node).to_a.last
  end

  add_offense(text_node) if text_node
end