Question

I have created a class that will automatically fill with data using the faker gem when an instance of the class is created. I am having trouble getting the Person object to populate. It is probably a clumsy syntax mistake.

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

I ran the code above in a ruby interpreter but I could not get the Class attributes to initialize, The following yields nillClass instead of String.

p = Person.new
puts p.firstname.class

Working Solution:

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
Was it helpful?

Solution

You have to have code in your initialize method initializating your attributes like:

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

You are just initializating the parameters in the initialize method and doing nothing with them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top