Easily declare private methods in Ruby

Written by Keith McDonnell. Last updated on Thursday, January 20, 2011.

Work in progress! Haven’t yet figured out how to declare method private fro m within an instance method.

When you have a large class file, private method definitions can often be too far away from their calling methods. You can end up ping ponging back and forward between calling and helper methods.

In a larger class file, I like to group co-operating methods together. Any called private methods are close to the methods where they are called. This can get ugly when using the composed method style.

def foo
  bar
  baz
end

def bar
end

private :bar

def baz
end

private :baz

Why not just use the private method above the method declarations? You must re-declare subsequent public methods to be so, which can get messy.

def foo
  bar
end

private

def bar
end

public 

def baz
end

Duplication easily removed with a class level macro (just dont say magic metaprogramming).

To that end I’ve created a gem: ruby-private. Here it is in action.

$ gem install ruby-private

$ irb -rrubygems

require 'ruby-private'

class Foo
  def bar
*  # You can declare this anywhere in the method. 
*  # However, at the top or bottom would be most noticable
*  private!
  end
end

Foo.private_methods
=> ["bar"]

Sweet, tasty sugar. Not the most useful code in the world but an interesting eperiment which helped me get re-aquinted with an old friend called Kernel.

Work in progress! Haven’t yet figured out how to declare method private fro m within an instance method.

ruby-private is available on ruby gems. You can check out the ruby-private source on github .

If you'd like to discuss this article, you can send me an email keith@dancingtext.com and/or publish an article online and link back to this page.