Note that there are some explanatory texts on larger screens.

plurals
  1. POCalling a subclass method from a superclass
    text
    copied!<p>Preface: This is in the context of a Rails application. The question, however, is specific to Ruby.</p> <p>Let's say I have a <code>Media</code> object. </p> <pre><code>class Media &lt; ActiveRecord::Base end </code></pre> <p>I've extended it in a few subclasses:</p> <pre><code>class Image &lt; Media def show # logic end end class Video &lt; Media def show # logic end end </code></pre> <p>From within the <code>Media</code> class, I want to call the implementation of <code>show</code> from the proper subclass. So, from Media, if <code>self</code> is a <code>Video</code>, then it would call Video's show method. If <code>self</code> is instead an <code>Image</code>, it would call Image's show method.</p> <p>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 <a href="https://stackoverflow.com/questions/512466/how-to-implement-an-abstract-class-in-ruby">Stack Overflow</a>) that abstract methods aren't the best way to deal with this in Ruby.</p> <p>With that in mind, I started <a href="https://stackoverflow.com/questions/3251429/fake-a-type-cast-in-ruby">researching typecasting</a> and discovered that this is also a relic of Java thinking that I need to banish from my mind when dealing with Ruby.</p> <p>Defeated, I started coding something that looked like this:</p> <pre><code>def superclass_method # logic this_media = self.type.constantize.find(self.id) this_media.show end </code></pre> <p>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.</p> <p>So, <strong>how can I call a subclass's implementation of a method from the superclass in Rails?</strong> Is there a better way than what I ended up (almost) implementing?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload