Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private module methods in Ruby

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.

like image 518
Daniel Beardsley Avatar asked Nov 25 '08 21:11

Daniel Beardsley


People also ask

Can a Ruby module have private 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.

What are private methods in Ruby?

What is a private method in Ruby? It's a type of method that you can ONLY call from inside the class where it's defined. This allows you to control access to your methods.

How do you call a private method in Ruby?

Using BasicObject#instance_eval , you can call private method.

What is the difference between private and protected methods in Ruby?

Both protected and private methods cannot be called from the outside of the defining class. Protected methods are accessible from the subclass and private methods are not. Private methods of the defining class can be invoked by any instance of that class. Public access is the default one.


1 Answers

I think the best way (and mostly how existing libs are written) to do this is by creating a class within the module that deals with all the logic, and the module just provides a convenient method, e.g.

module GTranslate   class Translator     def perform(text)       translate(text)     end      private      def translate(text)       # do some private stuff here     end   end    def self.translate(text)     t = Translator.new     t.perform(text)   end end 
like image 85
ucron Avatar answered Sep 18 '22 14:09

ucron