Don't the Ruby methods instance_eval() and send() negate the benefits of private visibility?

后端 未结 5 978
误落风尘
误落风尘 2021-01-21 12:45
w = Widget.new # Create a Widget
w.send :utility_method # Invoke private method!
w.instance_eval { utility_method } # Another way to invoke it
w.instance_eval { @x } # R         


        
5条回答
  •  长情又很酷
    2021-01-21 13:28

    The take home message is: don't bother.

    Ruby, like Python, absolutely sucks at sandboxing. If you try to lock something down, chances are there will always be some way to get around it. The multitude of ways to get a private attribute in Ruby proves my point.

    Why? Because they are designed to be that way. Both languages are designed so that they can be poked around with at runtime – it's what gives them their power. By sealing up your class, you're depriving others of the power that Ruby's metaprogramming provides.

    Java has reflection. C++ has pointers. Even Haskell has unsafePerformIO. If you want to protect your program, you will need to protect it on the operating system level, not using the language.

提交回复
热议问题