Rails 自定义弃用通知
有没有办法为我计划删除并想要记录其使用情况的应用程序中的方法和/或关联创建自定义弃用通知?我的一个模型中有一个关系,我不想继续使用它,并计划稍后重构代码。我想在每次调用该方法时在我的开发日志中创建一个通知。
我在 Ruby/Rails 中看到了使用某些方法时的弃用通知,并且认为必须有一种简单的方法来做到这一点。
像...
irb(main):001:0> 1.id
(irb):1: warning: Object#id will be deprecated; use Object#object_id
=> 3
Is there a way to create custom deprecation notices for methods and/or associations in my application that I plan on removing and want to log their usage? I have a relationship in one of my models that I don't want to use moving forward and plan to refactor the code at a later time. I would like to create a notice in my development log every time that method is called.
I have seen deprecation notices in Ruby/Rails when using certain methods, and figure there has to be an easy way to do this.
Something like...
irb(main):001:0> 1.id
(irb):1: warning: Object#id will be deprecated; use Object#object_id
=> 3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Rails 3 中,您可以使用:ActiveSupport 中的“deprecate”方法:
它将为您的方法创建一个别名并输出带有堆栈跟踪的警告。您还可以直接使用此功能的一部分,例如:
它将随消息一起输出堆栈跟踪。
In Rails 3 you can use the : "deprecate" method from ActiveSupport:
It will create an alias for your method and output a warning with a stack trace. You can also use parts of this functionality directly, e.g:
It will output the stack trace along with the message.
也许:
对于一段关系来说,有些类似的东西。
Maybe:
Something along those lines for a relationship.
在大多数情况下,您只需发出警告并调用新方法即可。
如果您需要或想要变得更高级,可以使用库或元编程,但总的来说,这不是实现如此简单的事情的好方法。您应该有充分的理由为如此简单的东西引入依赖项。
In the majority of cases, you can just raise a warning and call the new method.
There are libraries or metaprogramming if you need or want to get fancier, but in general that's not a good route to go for something this simple. You should have a pretty good reason to introduce a dependency for something this simple.
添加我的 2 美分:
如果您使用 Yard 而不是 rdoc,您的文档注释应如下所示:
最后,如果您遵守 tomdoc,让您的评论如下所示:
Adding my 2 cents:
If you're using Yard instead of rdoc, your doc comment should look like this:
Lastly, if you adhere to tomdoc, make your comment look like this: