[Ruby on Rails 3, Ruby on Rails 4] gems: faker, gimei, romankana

実際にありそうなユーザー名とメールアドレスを持つサンプルユーザーを自動的に作成する。

Contents

gemfile

gem 'faker'

データベースにサンプルユーザーを追加するRakeタスク

lib/tasks/sample_data.rake

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
    User.create!(name: "Example User",
                 email: "example@railstutorial.jp",
                 password: "foobar",
                 password_confirmation: "foobar")
    99.times do |n|
      name  = Faker::Name.name
      email = "example-#{n+1}@railstutorial.jp"
      password  = "password"
      User.create!(name: name,
                   email: email,
                   password: password,
                   password_confirmation: password)
    end
  end
end
$ bundle exec rake db:reset
$ bundle exec rake db:populate
$ bundle exec rake db:test:prepare

locale 対応

locale に対応している。
config/locales/ja.yml に設定が必要。

% bundle exec rails c
Loading development environment (Rails 3.2.14)
[3] pry(main)> name  = Faker::Name.name
=> "林 美咲"
[8] pry(main)> Faker::PhoneNumber.phone_number
=> "02-1144-0153"
[9] pry(main)> Faker::Address.city
=> "蒼空区"
[10] pry(main)> Faker::Address.state
=> "宮城県"
[12] pry(main)> Faker::Address.postcode
=> "921-1677"
[13] pry(main)> Faker::Internet.email
=> "@.net"
[14] pry(main)> Faker::Internet.user_name
=> "_"

日本人名を扱う

日本人の名前をフリガナ付きでランダムに返す。

ひらがな・カタカナ・ローマ字変換

どちらもMITライセンス。

gem 'gimei'
gem 'romankana'
% bundle exec rails c
Loading development environment (Rails 3.2.14)
[1] pry(main)> require 'gimei'
=> true
[2] pry(main)> require 'romankana'
=> true
[4] pry(main)> name1 = Gimei.new
=> #<gimei:0x007fdddd469598
 @first=
  #<gimei::First:0x007fdddd469570 @gender=:male, @name=["仁希", "にき", "ニキ"]>,
 @gender=:male,
 @last=#<gimei::Last:0x007fdddd4694f8 @name=["竹下", "たけした", "タケシタ"]>>
[5] pry(main)> name1.male?
=> true
[6] pry(main)> name1.kanji
=> "竹下 仁希"
[7] pry(main)> name1.katakana
=> "タケシタ ニキ"
[8] pry(main)> name1.katakana.to_roman
=> "takeshita niki"
[11] pry(main)> name1.katakana.to_roman.split.map{|s| s.capitalize}.join(" ")
=> "Takeshita Niki"

補遺

faker-japanese

% bundle exec rails c
Loading development environment (Rails 3.2.14)
[1] pry(main)> require 'faker/japanese'
=> true
[2] pry(main)> p Faker::Japanese::Name.name
"宅間 燕一"
=> "宅間 燕一"
[5] pry(main)> require 'faker'
=> true
[8] pry(main)> p Faker::Internet.email
"@.net"
=> "@.net"
[9] pry(main)> Faker::Internet.user_name
=> ""
[10] pry(main)> Faker::Config.locale = :en
=> :en
[11] pry(main)> Faker::Internet.user_name
=> "arnoldo_ziemann"
[12] pry(main)> p Faker::Internet.email
"stevie@murray.biz"
=> "stevie@murray.biz"
[16] pry(main)> name = Faker::Japanese::Name.name
=> "辻井 喜次郎"
[17] pry(main)> name.yomi
=> "ツジイ キジロウ"