Rails runner script not working

Any ideas why this is not working I get NoMethodErrorwhen I try to run the code below using rails runner.

Maybe I'm calling the rails runner incorrectly, sorry for the new Rails!

File location:

/app/scripts/data_import.rb

Team:

rails runner -e development DataImport.say_hi

Error:

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

the code:

class DataImport

  def say_hi
    puts "hi"
  end

end
+3
source share
4 answers

You call the instance method for the class, so it is undefined. Try using the class method instead:

class DataImport
  def self.say_hi
    puts "hi"
  end
end
+12
source

Change it to

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

Since you are accessing it as a class method, not as a class instance method, you need selfto declare the method as a class method.

+5
source

:

rails runner -e development "import = DataImport.new; import.say_hi"
+1

Answer: Many friends have already said that.

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

And the reason is that if you have a class and a method without yourself. You cannot call the ClassName.method class. You can call it like this if only the method is the self method of this class.

Otherwise, you can call as ClassName.new.method.

In your problem you can call as

DataImport.new.say_hi

And the class remains the same as you.

0
source

Source: https://habr.com/ru/post/1793296/


All Articles