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?
Just like classes and interfaces, we can declare delegates outside of classes or nested within classes. We can mark them private , public , or internal .
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 .
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.
Because delegate
returns a list of the symbols passed in you can chain the method calls like this:
private *delegate(:foo, :bar, :to => :baz)
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With