I'm new to Ruby (experienced with Python, C++ and C). I need to create a class that is only to be used by other classes and methods in a module. In Python, I'd just call it __classname. I'd use an empty typedef in C++. How do I do this in Ruby (or am I barking up the wrong tree and not doing this the "Ruby way"?)
Understanding Private Methods in RubyYou can only use a private method by itself. It's the same method, but you have to call it like this. Private methods are always called within the context of self .
there's no such thing as "a private section" in Ruby. To define private instance methods, you call private on the instance's class to set the default visibility for subsequently defined methods to private... and hence it makes perfect sense to define private class methods by calling private on the class's class, ie.
Private methods can't be called outside the class. Private methods can be called inside a class inside other methods.
Private instance/class methods for modulesDefining a private instance method in a module works just like in a class, you use the private keyword. You can define private class methods using the private_class_method method.
The most important thing to realize is that a class is nothing special. It's just an object. Per convention, classes are assigned to constants, but there is nothing that says they have to be.
And since classes are just objects like any other object, you make them private the same way that you make any other object private.
Here are the possibilities I can think of, in the order of increasing privateness:
my_awesome_library
→ MyAwesomeLibrary
), but in general, everything which is nested below that namespace, is considered private. In fact, besides Test::Unit::TestCase
, I cannot think of a single example of a three-level deep namespace that is actually expected to be used by client code.MyAwesomeLibrary::Internal::FfiStruct
:nodoc:
RDoc tag.snake_case
convention is just that: a convention.)send
seems to be in more widespread use than instance_variable_get
, though, which is why I consider instance variables to have a higher level of privacy than methods.Module.new
, Class.new
or Module#define_method
.Ex.:
module MyAwesomeLibrary
struct = Class.new(FFI::Struct) do
# ...
end
PublicInterface = Class.new do
define_method(:initialize) do |bar|
@foo = struct.new(bar)
end
end
end
And yes, this is the only way of achieving true 100% information hiding and encapsulation in Ruby.
However, the normal Ruby way would be to simply document the stuff as being private (maybe push it down a level of namespacing) and trust your fellow developers. In the Ruby community, this is sometimes summarized under the Python slogan "We are all consenting adults".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With