Ruby中的私有/受保护块?
Ruby似乎没有定义受保护/私有块的功能,例如:Ruby中的私有/受保护块?,ruby,access-specifier,Ruby,Access Specifier,Ruby似乎没有定义受保护/私有块的功能,例如: protected do def method end end 相比之下,这会更好 protected def method end public 在受保护的方法之后,您可能会忘记“public” 似乎可以使用元编程来实现这一点。有什么想法吗?既然你想按功能分组,你可以声明你所有的方法,然后使用protected(受保护的)和protected(私有的)来声明哪些方法是受保护的和私有的,后面跟你想受保护的方法的符号,对于pr
protected do
def method
end
end
相比之下,这会更好
protected
def method
end
public
在受保护的方法之后,您可能会忘记“public”
似乎可以使用元编程来实现这一点。有什么想法吗?既然你想按功能分组,你可以声明你所有的方法,然后使用protected(受保护的)和protected(私有的)来声明哪些方法是受保护的和私有的,后面跟你想受保护的方法的符号,对于private(私有的)也一样 下面的课程说明了我的意思。在这个类中,除了最后声明为protected和private的bar_protected和bar_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
事实上,我支持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
类模块
def带有_保护
别名_if_needed=lambda do |第一,第二|
alias_methods first,second if instance_methods.include?第二
结束
metaclass=classI决定接受这个答案,因为Ruby就是这样定义的。我假设对受保护的块进行元编程应该很容易,但显然不是。而且,最好不要进行元编程,直到您可以通过测试确认它是有效的。不过,感谢Chuck尝试解决这个问题:)看起来像是私人的,应该受到保护。我不知道为什么他们没有。我赞同@RyanHeneise所说的话——有人能提供更多关于这个公约的见解吗?