Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 679
Chris Avatar asked Mar 26 '13 17:03

Chris


People also ask

Can delegates be private?

Just like classes and interfaces, we can declare delegates outside of classes or nested within classes. We can mark them private , public , or internal .

Does Ruby have private methods?

Understanding Private Methods in RubyYou can only use a private method by itself. It's the same method, but you have to call it like this. Private methods are always called within the context of self .

What is delegate in Ruby on Rails?

On the Profile side we use the delegate method to pass any class methods to the User model that we want access from our User model inside our Profile model. The delegate method allows you to optionally pass allow_nil and a prefix as well. Ultimately this allows us to query for data in custom ways.


3 Answers

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

private *delegate(:foo, :bar, :to => :baz)
like image 186
twe4ked Avatar answered Nov 08 '22 04:11

twe4ked


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
like image 42
Arie Xiao Avatar answered Nov 08 '22 02:11

Arie Xiao


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
like image 40
Sebastian Palma Avatar answered Nov 08 '22 04:11

Sebastian Palma