4

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
Pan Thomakos
  • 34,082
  • 9
  • 88
  • 85
curv
  • 3,796
  • 4
  • 33
  • 48

4 Answers4

13

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
Pan Thomakos
  • 34,082
  • 9
  • 88
  • 85
5

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.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
1

An alternative to the already mentioned transformation of the instance method into a method of the singleton class is to create an object of the existing class and call the instance method in your runner:

rails runner -e development "import = DataImport.new; import.say_hi"
Holger Just
  • 52,918
  • 14
  • 115
  • 123
0

The answer is, Many friends already Posted that.

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

And the reason is, If you have a class and method without self. , You can't call the class like ClassName.method. You can call like this If only the method is a self method of that class.

Otherwise you can call like ClassName.new.method.

In your Problem, You can call like

DataImport.new.say_hi

And the Class remains the same as you written.

Jyothu
  • 3,104
  • 17
  • 26