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