May 2, 2015 by Daniel P. Clark

Private Module Methods in Ruby

So this is something I’ve looked into many times over the years and have never found an answer to.  But great news is that I’ve found a way!

It’s as simple as defining module methods as private within the singleton class.  Here’s how I did it in my gem PolyBelongsTo

My gem gets included into ActiveRecord::Base and these private methods are available for my other methods to use and my tests show that they are indeed private.  One sample ActiveRecord table I’ve named Squishy and this is the Minitest test I wrote to prove it’s private.

And it passes all green!  My other methods that call these pass as well! Yay!

If you were to do this without the Rails “Concern” way of doing it your code would look more like.

And anything you include it into will now have these private methods defined!  Hope you enjoyed this!  I’m very happy to have discovered it myself and hope it finds you well.

If you’re not planning on including the module you can do it like this.

Please feel free to comment, share, subscribe to my RSS Feed, and follow me on twitter @6ftdan!

God Bless!
-Daniel P. Clark

Image by Richard Scott via the Creative Commons Attribution-NonCommercial-NoDerivs 2.0 Generic License.

0 0 vote
Article Rating
Notify of
Newest Most Voted
Inline Feedbacks
View all comments
Daniel P. Clark
7 years ago
Reply to  Micah Geisel

Yes thanks! They’ve added several ways of defining a private method in more recent Ruby versions. The approach I’ve shared here works with Ruby 1.8

Piotr Szotkowski
7 years ago

In all of those cases presented in the blog my choice would be `module_function`, which makes the given `Module`’s methods callable on the `Module` itself and locally anywhere it’s included, but not from outside the places it’s included:

Daniel P. Clark
7 years ago

Awesome! That’s definitely handy if you’d like to be able to include the behavior. In the last example I’ve shown of a non-inclusive module the method access is exclusive. Which is something I rather like myself.