Other than self.class.send :method, args...
, of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code.
UPDATE:
@Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around. Visibility in Ruby is very different from that in Java. You're also quite right that private
doesn't work on class methods, though this will declare a private class method:
class Foo
class <<self
private
def bar
puts 'bar'
end
end
end
Foo.bar
# => NoMethodError: private method 'bar' called for Foo:Class
This is probably the most "native vanilla Ruby" way:
With some Ruby metaprogramming, you could even make it look like:
Ruby's metaprogramming is quite powerful, so you could technically implement any scoping rules you might want. That being said, I'd still prefer the clarity and minimal surprise of the first variant.
Let me contribute to this list of more or less strange solutions and non-solutions:
Nowadays you don't need the helper methods anymore. You can simply inline them with your method definition. This should feel very familiar to the Java folks:
And no, you cannot call a private class method from an instance method. However, you could instead implement the the private class method as public class method in a private nested class instead, using the
private_constant
helper method. See this blogpost for more detail.If your method is merely a utility function (that is, it doesn't rely on any instance variables), you could put the method into a module and
include
andextend
the class so that it's available as both a private class method and a private instance method.This is the way to play with "real" private class methods.
cheers
Unless I'm misunderstanding, don't you just need something like this:
Of course you could change the second definition to use your self.class.send approach if you wanted to avoid hardcoding the class name...