开发者

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!

开发者_StackOverflow中文版

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


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


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.


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"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜