如何编写卫生的 Ruby mixin?
假设我正在编写一个 mixin 模块,为第三方类添加功能。 显然,我希望第三方类及其客户端可以访问一些方法和实例变量。 这些构成了 mixin 模块的公共接口。
但我希望封装某些其他方法和实例变量。 我不希望我正在混合的类可以访问它们,特别是我不希望它们意外地覆盖、隐藏、冲突或以其他方式干扰 mixee 类的方法或实例变量 - 无论是那些当前可能存在的,或者如果第三方修改了我正在混合的类,将来可能会创建的。
我需要采取哪些预防措施(如果有的话)来确保我的 mixin 以这种方式“卫生”?
Say I'm writing a mixin module that adds functionality to a third-party class. Obviously some of the methods and instance variables I want to make accessible to the third-party class and its clients. These constitute the public interface of the mixin module.
But I want certain other methods and instance variables to be encapsulated. I don't want them to be accessible to the class I'm mixing into, and in particular I don't want them to accidentally override, shadow, conflict, or otherwise interfere with the mixee class's methods or instance variables -- either those that may currently exist, or those that may be created in the future if the third-party modifies the class I'm mixing into.
What precautions do I need to take, if any, to make sure my mixin is "hygienic" in this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许您可以创建一个子模块来包含所有实用程序方法。
Perhaps you could create a sub-module to contain all the utility methods.
创建一个单独的对象来封装您的功能和实例变量,并让 mixin 将可公开访问的方法委托给该对象。 现在您只需将一个实例变量与您的对象关联起来。 您甚至可以通过存储 {Mixee =>; 来避免这种情况。 委托} 模块中的哈希并在每个混合方法的开头进行查找。
Create a separate object to encapsulate your functionality and instance variables, and have the mixin delegate the publically accessible methods to that object. Now you only need to associate a single instance variable with your object. You could even dodge that by storing a {Mixee => Delegate} Hash in the module and doing a lookup at the start of each mixed in method.