2

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.

Community
  • 1
  • 1
Kevin Shu
  • 33
  • 1
  • 6
  • 1
    possible duplicate of [Private module methods in Ruby](http://stackoverflow.com/questions/318850/private-module-methods-in-ruby) – Schwern Mar 09 '15 at 17:02

3 Answers3

4
module Lib

  def self.private_function
   puts "k"
  end

  private_class_method(:private_function)

end

Lib.private_function #=> NoMethodError
steenslag
  • 79,051
  • 16
  • 138
  • 171
2

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
Ferdy89
  • 138
  • 1
  • 5
  • 2
    Ruby does not have macros. You mean "method" (or better, "the method [Module#private_class_method](http://ruby-doc.org/core-2.0.0/Module.html#method-i-private_class_method)"). – Cary Swoveland Mar 09 '15 at 17:33
  • Yeah, sorry for my language. It does behave like a classic macro, though – Ferdy89 Mar 10 '15 at 17:43
2

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.

sawa
  • 165,429
  • 45
  • 277
  • 381