Is overriding to_s methods in Ruby bad? [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
开发者_如何学CClosed 7 years ago.
Improve this questionI've been experimenting and find that I like redefining Object's to_s
methods.
Is this a bad idea or is it good practice?
No, you should feel free to override to_s
- there are no ill side-effects. As long as your new to_s
is more informative than the built-in (not exactly a high standard there), you're in the clear.
And they help make your test failures read better - sometimes by a lot - which is never a bad thing. Go for it!
I override to_s
all the time in my Rails project:
def to_s first_name + " " + last_name end
so that it's easier to show objects in the view:
<%= @person %>
It might be tricky to do that because sometimes, inspect
method just calls to_s
, and if that is altered, you might have trouble debugging. If you think altering to_s
may confuse you when you need to see the results by methods that rely on inspect
, such as p
, then maybe you need to redefine inspect
for that class at the same time. As long as you are sure what you are doing, you might want to do it.
It's not "bad" per se, but it isn't "good" either. It really depends on the context.
If you are doing this for a one-shot place (for example inside your rails app's /lib/
folder, for a particular app) it is probably alright (make sure to give the file a descriptive name, such as object_to_s_patch.rb
or similar, and that all patches are on the same place)
If you are doing a gem or a lib, on the other hand, I would not override it. Instead I'd add another method - Object.to_special_s
or something. But I'd also try not to touch Object if possible - If you can get by with using YourModule::to_s(object)
that'd be probably even better.
The reasoning behind this is that other people might be using Object.to_s
for other stuff, maybe in other libs. Monkeypatching it will produce clashes with those other libs.
The only exception when doing a gem that I can think of is when the main point (or one of the main points) of that library is actually overriding the method; in other words, you are literally making a lib that overrides Object.to_s
, and little else. I'd put some big warning on the documentation on that case. This way people using it will not get surprised.
精彩评论