Search code examples
rubydelegatesactivesupport

Make delegated methods private


I am delegating a couple of methods and also want them all to be private.

class Walrus
  delegate :+, :to => :bubbles

  def bubbles
    0
  end
end

I could say private :+, but I would have to do that for each method. Is there a way to either return a list of delegated methods or have delegate create private methods?


Solution

  • Monkey patch Module to add a helper method, just like what ActionSupport pack does:

    class Module
      def private_delegate *methods
        self.delegate *methods
        methods.each do |m|
          unless m.is_a? Hash
            private(m)
          end
        end
      end
    end
    
    # then
    class Walrus
      private_delegate :+, :to => :bubbles
    
      def bubbles
        0
      end
    end