Ruby方法instance_eval()和send()否定私有可见性的好处吗? [英] Don't the Ruby methods instance_eval() and send() negate the benefits of private visibility?

查看:106
本文介绍了Ruby方法instance_eval()和send()否定私有可见性的好处吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 } # Read instance variable of w

看上面与Widget类相关的示例(如下),send和instance_eval方法违反了私有可见性和受保护可见性提供的所有保护。如果是这样,为什么不能在Ruby中使用私有和受保护的访问权限呢,因为不能保证您的定义会得到遵守?

Looking at the example above which relates to the Widget class (below), the send and instance_eval methods violate all of the protections provided by private and protected visibility. If so, why bother with private and protected access in Ruby at all since there is no guarantee that your definitions will be honored?

class Widget
  def x # Accessor method for @x
   @x
  end
  protected :x # Make it protected
  def utility_method # Define a method
   nil
  end
  private :utility_method # And make it private
end


推荐答案

如果您真的要保护 Widget 的实例,则可以这样做(还有很多其他内容;这里的代码不是完整的安全解决方案,仅是指示性的):

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 <<self
    private
    def class_eval(&block)
      raise NotImplementedError.new('Widget is secure. Stop trying to hack me.')
    end
  end
end

Widget.freeze

这篇关于Ruby方法instance_eval()和send()否定私有可见性的好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆