Ruby中的私有/受保护块?

gsm*_*oza 8 ruby access-specifier

Ruby似乎没有像这样定义受保护/私有块的工具:

protected do
  def method
  end
end
Run Code Online (Sandbox Code Playgroud)

这比较好

protected 

def method 
end 

public
Run Code Online (Sandbox Code Playgroud)

你可能会忘记在受保护的方法后"公开".

似乎可以使用元编程实现这一点.有什么想法?

Bra*_*nar 16

由于您希望按功能分组,因此您可以声明所有方法,然后通过使用受保护的方法声明哪些方法受保护和私有,后跟要保护的方法的符号,以及私有方法相同.

以下课程显示了我的意思.在这个类中,所有方法都是公共的,除了bar_protected和bar_private,它们在结尾处被声明为protected和private.

class Foo

  def bar_public
    print "This is public"
  end

  def bar_protected
    print "This is protected"
  end

  def bar_private
    print "This is private"
  end

  def call_protected
    bar_protected
  end

  def call_private
    bar_private
  end

  protected :bar_protected

  private :bar_private

end
Run Code Online (Sandbox Code Playgroud)

  • 似乎私人的和受保护的应该是障碍。我不知道为什么他们没有。 (2认同)

Chu*_*uck 9

我实际上支持bodnarbm的解决方案并且不建议这样做,但是因为我无法通过元编程挑战,所以这是一个将完成此任务的黑客:

class Module
  def with_protected
    alias_if_needed = lambda do |first, second|
      alias_method first, second if instance_methods.include? second
    end
    metaclass = class<<self; self end
    metaclass.module_eval {|m| alias_if_needed[:__with_protected_old__, :method_added]}
    def self.method_added(method)
      protected method
      send :__with_protected_old__ if respond_to? :__with_protected_old__
    end
    yield
    metaclass.module_eval do |m|
      remove_method :method_added
      alias_if_needed[:method_added, :__with_protected_old__]
    end
  end
end
Run Code Online (Sandbox Code Playgroud)