Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails runner script not working

Any ideas why this doesn't work, I get a NoMethodErrorwhen I try and run the code below via rails runner.

Maybe I am calling the rails runner incorrectly, sorry new to Rails!

File location:

/app/scripts/data_import.rb

Command:

rails runner -e development DataImport.say_hi

Error:

undefined method `say_hi' for DataImport:Class (NoMethodError)

Code:

class DataImport

  def say_hi
    puts "hi"
  end

end
like image 216
curv Avatar asked Dec 01 '22 03:12

curv


2 Answers

You are calling an instance method on the class, so it's undefined. Try making your method a class method instead:

class DataImport
  def self.say_hi
    puts "hi"
  end
end
like image 112
Pan Thomakos Avatar answered Dec 04 '22 05:12

Pan Thomakos


Change it to

class DataImport
  def self.say_hi
    puts "hi"
  end
end

Since you're accessing it as a class method and not a method on an instance of the class, you need the self to declare the method as a class method.

like image 22
Andrew Marshall Avatar answered Dec 04 '22 06:12

Andrew Marshall