Make delegated methods private
Asked Answered
R

3

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?

Ronnieronny answered 26/3, 2013 at 17:4 Comment(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?Nelson
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_10Ronnieronny
Then, the way you wrote was misleading.Nelson
T
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
Toul answered 26/3, 2013 at 17:35 Comment(0)
R
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)
Reply answered 8/3, 2016 at 2:59 Comment(2)
No monkeypatching and splat power. This guy deserves a medal.Transact
This also works with Forwardable#def_delegators: private(*def_delegators(:delegatee, :foo, :bar)) ruby-doc.org/stdlib-2.5.0/libdoc/forwardable/rdoc/…Pedaias
T
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
Toul answered 26/3, 2013 at 17:35 Comment(0)
M
4

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
Munda answered 23/12, 2019 at 13:51 Comment(1)
I do know the question isn't Rails tagged.Care

© 2022 - 2024 — McMap. All rights reserved.