将委派方法设为私有

时间:2013-03-26 17:04:51

标签: ruby delegates activesupport

我委托了几种方法,并希望它们都是私有的。

class Walrus
  delegate :+, :to => :bubbles

  def bubbles
    0
  end
end

我可以说private :+,但我必须为每种方法都这样做。有没有办法返回委托方法列表或委托创建私有方法?

3 个答案:

答案 0 :(得分:52)

因为delegate返回传入的符号列表,所以可以链接方法调用,如下所示:

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

答案 1 :(得分:5)

Monkey patch Module添加帮助方法,就像ActionSupport包一样:

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

答案 2 :(得分:0)

对于那些使用Rails 6+的用户,感谢you can pass the private option to make the delegated methods private现在的Tomas Valent:

delegate :method, to: :object, private: true