Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

Because delegate returns a list of the symbols passed in you can chain the method calls like this:

private *delegate(:foo, :bar, :to => :baz)

For those using Rails 6+, thanks to Tomas Valent now you can pass the private option to make the delegated methods private:

delegate :method, to: :object, private: true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top