Papouche Guinslyzinho
Papouche Guinslyzinho

Reputation: 5458

gem Faker adding a method

I'm seeding some Posts (seeds.rb). But I would like to add locally a method (past_week) in Faker. And I'm getting an error

seeds.rb

Post.create(
    :title => Faker::Lorem.words(4),
    :content => Faker::Lorem.paragraph(2)
    :created_at => Faker::Date.past_week
    )

faker.rb (in my ~/.rvm/gems/ruby-2.1.0/faker1-3-0

require 'time'
require 'date'
require 'faker/date'

in my date.rb (in my ~/.rvm/gems/ruby-2.1.0/faker1-3-0/lib

module Faker
  class Date < Base
    class << self
      def past_week
        #return a random day in the past 7 days
        today = Date.today
        today = today.downto(today - 7).to_a
        today.shuffle[0]

      end
    end
  end
end

my error

NoMethodError: undefined method `today' for Faker::Date:Class
/home/userlaptop/.rvm/gems/ruby-2.1.0/gems/faker-1.3.0/lib/faker.rb:138:in `method_missing'
/home/userlaptop/.rvm/gems/ruby-2.1.0/gems/faker-1.3.0/lib/faker/date.rb:5:in `past_week'
/home/userlaptop/development/public/project/jed/db/seeds.rb:21:in `<top (required)>'

Upvotes: 0

Views: 773

Answers (1)

vee
vee

Reputation: 38645

Because you've named your class Date, today is not found as you do not have that method defined. In order to reference the ruby Date class, prefix the class with a scope resolution operator:

module Faker
  class Date < Base
    class << self
      def past_week
        #return a random day in the past 7 days
        today = ::Date.today
        today = today.downto(today - 7).to_a
        today.shuffle[0]

      end
    end
  end
end

Upvotes: 1

Related Questions