I’m currently working on a Rails project, and have found times where it’s easiest to do
if object.class == Foo
...
else if object.class == Bar
...
else
...
I started doing this in views where I needed to display different objects in different ways, but have found myself using it in other places now, such as in functions that take objects as arguments. I’m not precisely sure why, but I feel like this is not good practice.
If it’s not good practice, why so?
If it’s totally fine, when are times that one might want to use this specifically?
Thanks!
Not sure why that works for you at all. When you need to test whether
objectis instance of classFooyou should useBut it’s not a good practice in Ruby anyway. It’d much better to use polymorphism whenever it’s possible. For example, if somewhere in the code you can have object of two different classes and you need to display them differently you can define
displaymethod in both classes. After that you can callobject.displayand object will be displayed using method defined in the corresponding class.Advantage of that approach is that when you need to add support for the third class or a whole bunch of new classes all you’ll need to do is define
displaymethod in every one of them. But nothing will change in places where you actually using this method.