Reputation: 47
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.
Upvotes: 1
Views: 1450
Reputation: 714
self
in the context of the class method is the class itself. So can access every class method defined in the current class. Examples above are very useful but I want to give you another one which is a little bit more clear (in my opinion):
class MyClass
def self.method1
p self
puts "#{method2}"
end
def self.method2
puts "Hello Ruby World!\n I am class method called from another class method!"
end
end
MyClass.method1
# => MyClass
# => Hello Ruby World!
I am class method called from another class method!
Upvotes: 1
Reputation: 6852
For you to understand what is going on, you've got to check the scope inside the class method.
class Foo
def self.bar
puts self
end
end
Foo.bar
# => Foo
When Foo.bar
is called, Foo
is returned. Not an instance, but the class. That means you can access every class method of Foo
inside the self.bar
method.
class Foo
def self.bar
puts "bar was called"
self.qux
end
def self.qux
puts "qux was called."
end
end
Foo.bar
# => bar was called
# qux was called.
Upvotes: 1
Reputation: 78
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' )
Upvotes: 1