I have a two part question
Best-Practice
- I have an algorithm that performs some operation on a data structure using the public interface
- It is currently a module with numerous static methods, all private except for the one public interface method.
- There is one instance variable that needs to be shared among all the methods.
These are the options I can see, which is the best?:
- Module with static ('module' in ruby) methods
- Class with static methods
- Mixin module for inclusion into the data structure
- Refactor out the part of the algorithm that modifies that data structure (very small) and make that a mixin that calls the static methods of the algorithm module
Technical part
Is there any way to make a private Module method?
module Thing
def self.pub; puts "Public method"; end
private
def self.priv; puts "Private method"; end
end
The private
in there doesn't seem to have any effect, I can still call Thing.priv
without issue.
Unfortunately,
private
only applies to instance methods. The general way to get private "static" methods in a class is to do something like:Admittedly I haven't played with doing this in modules.
Make a private module or class
Constants are never private. However, it's possible to create a module or class without assigning it to a constant.
So an alternative to
:private_class_method
is to create a private module or class and define public methods on it.Usage:
See the docs for Module.new and Class.new.
What's about storing methods as lambdas within class variables/constants?
For test:
Here we see that C can be successfully used by B and D, but not from outside.
A nice way is like this
I think the best way (and mostly how existing libs are written) do this by making a class within the module that deals with all the logic, and the module just provides a convenient method, e.g.