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.

#base#include#included#method#methods#module#private#rails#ruby

4
Leave a Reply

avatar
2 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
Piotr SzotkowskiDaniel P. ClarkMicah Geisel Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Micah Geisel
Guest
Micah Geisel
Daniel P. Clark
Guest

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
Guest

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
Guest

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.