13

I am trying to add a method to my seeds.rb so that I don't have to write a bunch of verbose code. However, depending on the placement of the create_deliverable method I get one of two error messages when running db:setup.

When method is before call

rake aborted! private method 'create_deliverable' called for #

When method is after call

rake aborted! undefined method `create_deliverable' for #

Is it not possible to uses methods in seeds.rb? Am I somehow calling the method incorrectly (I've tried calling with and without the self.)?

Method

def create_deliverable(complexity, project_phase_id, deliverable_type_id)
  Deliverable.create(:name => (0...8).map{65.+(rand(25)).chr}.join,
      :size => 2 + rand(6) + rand(6),
      :rate => 2 + rand(6) + rand(6),
      :deliverable_type_id => deliverable_type_id,
      :project_phase_id => project_phase_id,
      :complexity => complexity)
end

Calling Code

@wf_project.project_phases.each do |phase|
  DeliverableType.find_by_lifecycle_phase(phase.lifecycle_phase_id).each do
    |type|
    self.create_deliverable("Low", type.id, phase.id)

    self.create_deliverable("Medium", type.id, phase.id)

    self.create_deliverable("High", type.id, phase.id)
  end
end
ahsteele
  • 26,243
  • 28
  • 134
  • 248

3 Answers3

21

Make sure you define the method before calling it:

def test_method
  puts "Hello!"
end

test_method
Joe Stepowski
  • 656
  • 1
  • 6
  • 8
  • 3
    This is actually a better answer, because seeds.rb doesn't define a class, so public/private methods don't matter. – Ramsy de Vos Aug 17 '17 at 15:47
15

If you're going to use self., use it on the method definition, not the call.

def self.create_deliverable(...)
    ...
end
...
create_deliverable("Low", type.id, phase.id)
...

It's my understanding that .rb files without a class definition get wrapped in an anonymous ruby class when they are run, so defining the method on self should work just fine.

localshred
  • 2,244
  • 1
  • 21
  • 33
  • 7
    +1 for the explanation about how `.rb` files without a class definition get wrapped in an anonymous ruby class – ahsteele Nov 17 '09 at 18:48
7

Looks to me like you placed your create_deliverable method after private access modifier in your script. Put it after public.

public

    def create_deliverable(complexity, project_phase_id, deliverable_type_id)
      Deliverable.create(:name => (0...8).map{65.+(rand(25)).chr}.join,
          :size => 2 + rand(6) + rand(6),
          :rate => 2 + rand(6) + rand(6),
          :deliverable_type_id => deliverable_type_id,
          :project_phase_id => project_phase_id,
          :complexity => complexity)
    end
private # to keep the rest of methods private
wscourge
  • 10,657
  • 14
  • 59
  • 80
Alex Polkhovsky
  • 3,340
  • 5
  • 29
  • 37
  • 3
    seeds.rb doesn't define any classes, so public and private doesn't matter. What matters is that you define the method before executing it. – Ramsy de Vos Aug 17 '17 at 15:48