Calling a subclass method from a superclass
Posted
by
Shaun
on Stack Overflow
See other posts from Stack Overflow
or by Shaun
Published on 2011-01-30T22:34:24Z
Indexed on
2011/01/30
23:25 UTC
Read the original article
Hit count: 285
Preface: This is in the context of a Rails application. The question, however, is specific to Ruby.
Let's say I have a Media
object.
class Media < ActiveRecord::Base
end
I've extended it in a few subclasses:
class Image < Media
def show
# logic
end
end
class Video < Media
def show
# logic
end
end
From within the Media
class, I want to call the implementation of show
from the proper subclass. So, from Media, if self
is a Video
, then it would call Video's show method. If self
is instead an Image
, it would call Image's show method.
Coming from a Java background, the first thing that popped into my head was 'create an abstract method in the superclass'. However, I've read in several places (including Stack Overflow) that abstract methods aren't the best way to deal with this in Ruby.
With that in mind, I started researching typecasting and discovered that this is also a relic of Java thinking that I need to banish from my mind when dealing with Ruby.
Defeated, I started coding something that looked like this:
def superclass_method
# logic
this_media = self.type.constantize.find(self.id)
this_media.show
end
I've been coding in Ruby/Rails for a while now, but since this was my first time trying out this behavior and existing resources didn't answer my question directly, I wanted to get feedback from more-seasoned developers on how to accomplish my task.
So, how can I call a subclass's implementation of a method from the superclass in Rails? Is there a better way than what I ended up (almost) implementing?
© Stack Overflow or respective owner