Cheatsheet about extending Ruby classes

Category: Ruby :: Published at: 10.06.2022

Here is my small cheatsheet which will help you to extend any Ruby class.

I found out it very helpful and i hope, it will also be a nice help for you.

 

Ancestor - any superclass of our class. It is a parent of our class, parent of a parent of our class etc.

We can check all ancestors of our class by a calling method:

class Demo; end

Demo.ancestors
=> [Demo, Object, Kernel, BasicObject]

Below you can find all basic types of extending a class in Ruby.

 

INCLUDE

  • An INCLUDE directive let us to include any module inside our Class.
  • We can't include class into a class (module is just a group of methods, class generates an object in Ruby)

Example of use:

module Honda
  def civic
    puts "Honda Civic"
  end
end

class Car
  include Honda
end

Car.new.civic
=> "Honda Civic"

By using Liskov principle (from SOLID) we can overrite method of a parent or extend its functionality (with using super):

module Honda
  def civic
    puts "Honda Civic"
  end
end

class Car
  include Honda

  def civic
    super
    puts "Out of stock"
  end
end

Car.new.civic
=> "Honda Civic"
=> "Out of stock"

 

EXTEND

  • takes all the methods from the module and place them inside your class as a class methods
  • unlike INCLUDEEXTEND will not add the module to the ancestors
module Honda
  def civic
    puts "Honda Civic"
  end
end

class Car
  extend Honda
end

Car.civic
=> "Honda Civic"

 

PREPEND

  • similar to the INCLUDE, but it changes the order of classes
  • if you prepend a module into a class, the class will become a parent of this module so you can use super inside a module
module Honda
  def civic
    super
    puts "Honda Civic"
  end
end

class Car
  prepend Honda

  def civic
    puts "Car is not available"
  end
end

Car.new.civic
=> "Car is not available"
=> "Honda Civic"


- Click if you liked this article

Views: 459