Kevin Shu
Kevin Shu

Reputation: 33

What is the best way to hide module method in ruby?

In JavaScript, it's easy to hide function or variable in closure.
In ruby, private doesn't work for Module method.
Is there best practice to do so?

module Lib

  def self.public_function
    private_function
  end

  private # Does not work
  def self.private_function

  end

end

Lib.public_function

I've read this post: Private module methods in Ruby
But the best answer is not simple enough for me.

Upvotes: 2

Views: 3109

Answers (4)

justapilgrim
justapilgrim

Reputation: 6872

def returns the function name, so combined with private_class_method, you can achieve this:

module Math
  def self.sum
    1 + 1
  end

  private_class_method def self.subtract
    1 - 1
  end
end

Upvotes: 0

sawa
sawa

Reputation: 168101

private only makes the receiver obligatorily implicit, and is not suited for the purpose of hiding a method. protected makes the method accessible only within the context of the receiver class, and works better for the purpose of hiding the method.

Upvotes: 2

Ferdy89
Ferdy89

Reputation: 138

You can achieve private methods in a module with the macro private_class_method like this:

def self.private_function
end
private_class_method :private_function

Upvotes: 2

steenslag
steenslag

Reputation: 80065

module Lib

  def self.private_function
   puts "k"
  end

  private_class_method(:private_function)

end

Lib.private_function #=> NoMethodError

Upvotes: 4

Related Questions