`respond_to_missing?` 的第二个参数对任何事情都有用吗? [英] Is `respond_to_missing?`'s second argument useful for anything?
问题描述
在使用 method_missing
时Ruby,几乎总是一个好主意来定义respond_to_missing?
.
When using method_missing
in Ruby, it's almost always a good idea to define respond_to_missing?
as well.
respond_to_missing?
需要两个参数;我们正在检查的方法的名称(symbol
),以及一个指示我们是否应该在检查中包含私有方法的布尔值(include_all
).
respond_to_missing?
takes two arguments; the name of the method we're checking (symbol
), and a boolean which indicates whether we should include private methods in our check (include_all
).
现在我感到困惑的是:method_missing
不接受任何可能指示它是否应该调用私有方法的参数,如 respond_to_missing?
确实如此.此外,method_missing
会被调用而不管原始方法调用是在公共上下文中还是私有上下文中,也不管 respond_to_missing?
在适当的上下文中返回给定的方法.所以method_missing
的所有操作都是可以访问的公开.
Now here's what I'm confused about: method_missing
doesn't take any arguments which might indicate to it whether it should call private methods or not, as respond_to_missing?
does. Furthermore, method_missing
gets called regardless of whether the original method call was in a public or private context, and regardless of what respond_to_missing?
returns for the given method in the appropriate context. So all operations of method_missing
are accessible publicly.
如果是这样,那么 的第二个参数有什么作用?respond_to_missing?
(include_all
) 服务?给定的对象是否响应缺失的方法不受调用缺失方法的上下文的影响,那么为什么还要有这个参数呢?
If that's the case, then what purpose does the second argument to respond_to_missing?
(include_all
) serve? Whether the given object responds to a missing method cannot be affected by the context in which the missing method was called, so why even have this argument at all?
推荐答案
我认为 respond_to_missing?
有第二个参数,原因与 respond_to?
确实如此.在这两种情况下,它都允许代码以尊重方法隐私的方式询问对象它响应哪些方法.如果使用得当,它可以帮助您更好地封装对象.
I think that respond_to_missing?
has a second argument for the same reason that respond_to?
does. In both cases, it allows code to ask an object what methods it responds to in a way that respects method privacy. If used properly, it can help you encapsulate your objects better.
您已经指出 method_missing
中缺少的一个特性,即它应该有一个参数,说明该方法是在公共还是私有上下文中调用的.也许有一天 method_missing
会有这个功能.在此之前,通过 method_missing
实现的对象的所有功能都将有效地公开,但您仍然可以阻止人们在您的文档中和通过 respond_to_missing?
使用它.
You have pointed out a missing feature in method_missing
, namely that it should have an argument that says whether the method was called in a public or private context. Maybe method_missing
will have that feature some day. Until then, all functionality of the object that is implemented through method_missing
will effectively be public, but you can still discourage people from using it in your documentation and via respond_to_missing?
.
这篇关于`respond_to_missing?` 的第二个参数对任何事情都有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!