17

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?

3
  • This part is not clear: "I could say private :+, but then every method I delegate has to be immediately, explicitly made private". Why is that?
    – sawa
    Mar 26, 2013 at 17:25
  • If I want to delegate 10 methods and have them all be private, I would have to do this: delegate :method_1, :method_2, :method_3, :method_4, :method_5, :method_6, :method_7, :method_8, :method_9, :method_10, :to => :bubbles then private :method_1, :method_2, :method_3, :method_4, :method_5, :method_6, :method_7, :method_8, :method_9, :method_10
    – Chris
    Mar 26, 2013 at 18:18
  • Then, the way you wrote was misleading.
    – sawa
    Mar 26, 2013 at 18:40

3 Answers 3

60

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

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

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
0
3

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
1
  • I do know the question isn't Rails tagged. Dec 23, 2019 at 13:51

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.