Faker Gem的类初始化

时间:2013-05-06 20:08:02

标签: ruby faker

我创建了一个类,当创建类的实例时,它将使用faker gem自动填充数据。我无法填充Person对象。这可能是一个笨拙的语法错误。

require 'rubygems'
require 'faker' 

class Person
  attr_accessor :firstname , :lastname, :phonenumber, :workaddress, :bio, :email

  def initialize(firstname = Faker::Name.first_name ,
    lastname = Faker::Name.last_name,
    phonenumber = Faker::PhoneNumber.phone_number,
    workaddress = "#{Faker::Address.street_name}, 
        #{Faker::Address.city}, #{Faker::Address.state_abbr}, #{Faker::Address.zip}",
    bio = 'bla bla bla',
    email = Faker::Internet.email)
  end

end

我在ruby解释器中运行上面的代码,但是我无法初始化Class属性,以下产生nillClass而不是String。

p = Person.new
puts p.firstname.class

工作解决方案:

def initialize(firstname = Faker::Name.first_name ,lastname =Faker::Name.last_name,phonenumber = Faker::PhoneNumber.phone_number,workaddress = "#    {Faker::Address.street_name}, #{Faker::Address.city}, #{Faker::Address.state_abbr}, #{Faker::Address.zip}",bio = "#{Lolem.new.words(7)}", email = Faker::Internet.email)
    @firstname = firstname
    @lastname = lastname
    @phonenumber = phonenumber
    @workaddress = workaddress
    @bio = bio
    @email = email
end

1 个答案:

答案 0 :(得分:2)

您必须在initialize方法中使用初始化属性的代码,如:

def initialize(firstname = Faker::Name.first_name, ...)
  @firstname = firstname
  # ...
end

您只是初始化初始化方法中的参数,并且不对它们执行任何操作。