LoginSignup
2
1

More than 5 years have passed since last update.

config/locales/(model_name)/ja.yml に i18n の雛形ファイルを作成するRakeタスク

Posted at
lib/tasks/locale.rake
namespace :locale do
  desc "create locale file"
  task :create, [:model_name] => :environment do |task, args|
    model_name = args['model_name']
    const = model_name.camelize.constantize
    path = Pathname("config/locales/#{model_name.underscore}/ja.yml")
    FileUtils.mkdir_p(path.dirname)
    yml = ERB.new(<<-YML
ja:
  activerecord:
    models:
      <%= model_name.underscore %>: <%= model_name.camelize %>
    attributes:
      <%= model_name.underscore %>:
        <% const.column_names.each do |col| %>
        <%= col %>: <%= col %>
        <% end %>
YML
    ).result(binding)
    File.write(path, yml.gsub(/\n\s*\n/, "\n"))
    puts "created: #{path}"
  end

  task create_all: :environment do
    model_names = Dir['app/models/*.rb'].map{|path| path.match(/app\/models\/(.*)\.rb/); $1 }.map(&:camelize)

    model_names.each do |model_name|
      next if model_name == 'ApplicationRecord'
      Rake::Task["locale:create"].execute(Rake::TaskArguments.new([:model_name], [model_name]))
    end
  end
end
$ bin/rake locale:create[User]

config/locales/user/ja.yml
ja:
  activerecord:
    models:
      user: User
    attributes:
      user:
        id: id
        created_at: created_at
        updated_at: updated_at

のように作ってくれる

2
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
2
1