Search code examples
rubyclass-method

Ruby On Rails: Can I call a class method from a class method?


I need to know if I can call a class method from a class method and how.

I've got a class on my model and one of my class methods is getting long:

def self.method1(bar)
  # Really long method that I need to split
  # Do things with bar
end

So I want to split this method in 2 methods. Something like that

def self.method1(bar)
  # Do things with bar
  # Call to method2
end

def self.method2(bar)
  # Do things
end

Both of them must be class methods

How can I call this method2 from method1?

Thanks.


Solution

  • This is answered here: Calling a class method within a class

    To re-iterate:

    def self.method1(bar)
      # Do things with bar
      # Call to method2
      method2( bar )
    end
    

    A full class example:

    class MyClass
      def self.method1(bar)
        bar = "hello #{ bar }!"
        method2( bar )
      end
    
      def self.method2(bar)
        puts "bar is #{ bar }"
      end
    end
    
    MyClass.method1( 'Foo' )