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

后端 未结 5 918
误落风尘
误落风尘 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:42

    If you really want to protect instances of Widget, you can do this (and a bunch of other stuff; the code here is not a complete security solution, merely indicative):

    class Widget
    
      def some_public_method
        ...
      end
    
      private
    
      def utility_method
        ...
      end
    
      def send(method, *args, &block)
        raise NotImplementedError.new('Widget is secure. Stop trying to hack me.')
      end
    
      def instance_eval(&block)
        raise NotImplementedError.new('Widget is secure. Stop trying to hack me.')
      end
    
      class <

提交回复
热议问题