Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call another method from a self method with ruby?

# app/models/product.rb
class Product < ApplicationRecord
  def self.method1(param1)
    # Here I want to call method2 with a parameter
    method2(param2)
  end

  def method2(param2)
    # Do something
  end
end

I call method1 from controller. When I run the program. I got an error:

method_missing(at line method2(param2))
.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0/lib/active_record/relation/batches.rb:59:in `block (2 levels) in find_each
...
like image 306
s_zhang Avatar asked Dec 07 '16 09:12

s_zhang


People also ask

How do you call a self method in Ruby?

One practical use for self is to be able to tell the difference between a method & a local variable. It's not a great idea to name a variable & a method the same. But if you have to work with that situation, then you'll be able to call the method with self. method_name .

How do you access class methods in Ruby?

Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.

How do you run a method in Ruby?

It's easy -- just create a file with the extension . rb , navigate to that file's directory from the command line, and run it using $ ruby filename. rb (the dollar sign is just the command prompt).


2 Answers

class Product < ApplicationRecord
  def self.method1(param1)
    # Here I want to call method2 with a parameter
    method2(param2)
  end

  def self.method2(param2)
    # Do something
  end
end

Explanation: first one is a class method, the latter was an instance method. Class methods don't need a receiver (an object who call them), instance methods need it. So, you can't call an instance method from a class method because you don't know if you have a receiver (an instanciated object who call it).

like image 113
Ursus Avatar answered Sep 21 '22 15:09

Ursus


It does not work because method2 is not defined for Product object.

method2 is an instance method, and can be called only on the instance of Product class.

like image 29
Andrey Deineko Avatar answered Sep 22 '22 15:09

Andrey Deineko