Inheritance

Optional Node
Collapse Content

Inheritance lets you create child classes that inherit methods (and variables) from parent classes. See this page on Inheritance for a quick overview of the concepts involved.

Inheritance

Use < after a class name to make it inherit from another class. For example, Dog inherits from Animal which inherits from LifeForm:

class LifeForm    
  def initialize
    @size = 1
  end

  def size
    @size
  end

  def grow
    @size += 1
  end    
end

class Animal < LifeForm
  def move
    puts "Moved.."
  end
end

class Dog < Animal
  def bark
    puts "Woof!"
  end
end

Any dog you create will now inherit the methods from all its superclasses. (The output is shown after #=>).

dog = Dog.new
dog.move  #=> Moved..
puts dog.size #=> 1
dog.grow  
puts dog.size   #=> 2

Challenge

Until now, everything we've created has been focused around storing and retrieving products. But we may want to store other data, such as users or comments. It would be redundant to re-write an entire Database, Controller and Router for each new type. Instead, let's refactor the code so common functionality of the Controller and Database can be shared by many different categories.

In Rails, specific models and controllers inherit from Rails library classes, so let's use inheritance in a similar manner. The goal of this challenge is to move out product-specific code from your Model and Controller classes to a ProductModel and ProductsController. This would make it easier for you to later add other models and controllers, and add custom code to each one as needed. You can refactor the code as you want or follow the guidelines below.

Guidelines

  1. Create a ProductModel class below Model that inherits from it. Create a ProductsController class below Controller that inherits from it.
  2. Create 2 initialize methods to set things up in the following classes:
  3. Add one to Router to create a ProductsController variable that can be called when processing input. (Call that variable from within your method that gets input.)
  4. Add one to ProductsController that sets a @Model variable to the ProductModel class. (Call that variable from your controller methods.)
  5. Create an empty array for storing products inside ProductModel instead of Model. Move the self.create method from Model to ProductModel.
  6. Adjust your code as needed.

Your code now does the same thing, but can be modified to add additional models and controllers in the future that will inherit common functionality but can also have their own custom code.

Challenge

Refactor your code to use inheritance.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]