Chapter 9 - Mixins

Exercise 1: Inheritance abuse

We have Drill and ElectricCar classes that need power_level and power_level= attribute accessor methods, a charge method, and a rev_motor method. We also have a Phone class that only needs the power_level, power_level=, and charge methods.

See if you can create a Motorized module with a rev_motor method, and a BatteryPowered module with power_level, power_level=, and charge methods. Remember to avoid using an initialize method in a module; you’ll probably need to use the ||= operator to set an initial value for the power level.

Then, mix those modules into the Drill, ElectricCar, and Phone classes, as appropriate. The Drill and ElectricCar classes should have power_level, power_level=, charge, and rev_motor methods. The Phone class should have all of those methods except the rev_motor method.

module Motorized
  def rev_motor
    puts "Revving motor!"
  end
end

module BatteryPowered
  attr_writer :power_level

  def power_level
    @power_level ||= 0
  end

  def charge
    self.power_level += 1
  end
end

class Drill
  include Motorized
  include BatteryPowered
end

class ElectricCar
  include Motorized
  include BatteryPowered
end

class Phone
  include BatteryPowered
end

Here’s some code to try out the above classes:

drill = Drill.new
drill.charge
puts drill.power_level

car = ElectricCar.new
car.charge
car.rev_motor

phone = Phone.new
phone.charge
phone.charge
puts phone.power_level

Here’s the output:

1
Revving motor!
2