【发布时间】:2010-11-02 21:57:37
【问题描述】:
Ruby 似乎没有像这样定义受保护/私有块的工具:
protected do
def method
end
end
这个比较好
protected
def method
end
public
您可能会忘记在受保护的方法之后“公开”。
似乎可以使用元编程来实现这一点。有什么想法吗?
【问题讨论】:
标签: ruby access-specifier
Ruby 似乎没有像这样定义受保护/私有块的工具:
protected do
def method
end
end
这个比较好
protected
def method
end
public
您可能会忘记在受保护的方法之后“公开”。
似乎可以使用元编程来实现这一点。有什么想法吗?
【问题讨论】:
标签: ruby access-specifier
由于您想按功能分组,您可以声明所有方法,然后使用 protected 后跟要保护的方法的符号来声明哪些方法是受保护的和私有的,私有方法也是如此。
下面的课程说明了我的意思。在这个类中,所有方法都是公共的,除了 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
【讨论】:
我实际上赞同 bodnarbm 的解决方案并且不建议这样做,但由于我无法放弃元编程挑战,这里有一个可以完成此任务的 hack:
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
【讨论】: