在包含模塊的同時,是否有簡明的方法來限制模塊內的方法可見性?換句話說,我想用僅包含模塊中使用的輔助方法來限制污染類。在包含模塊時避免類污染
module Bar
def call
hide_me
end
private
# make this method only callable within this module
def hide_me
'visible'
end
end
class Foo
include Bar
def unrelated_method
hide_me
end
end
# that's ok
Foo.new.call #=> 'visible'
# that's not
Foo.new.unrelated_method #=> 'visible'
我確定通過Bar.instance_method(:hide_me).bind(self).call
調用它,我只是不想擔心一些模塊來訪問或重新定義一個輔助方法。通過包括模塊類,然後取消定義不需要包括方法
module Bar
def call
BarClass.new.call
end
class BarClass
def call
hide_me
end
private
def hide_me
puts "invisible"
end
end
end
class Foo
include Bar
def call_bar
call
end
def this_method_fails
hide_me
end
end
這似乎是最乾淨的方式,謝謝! –