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.
Here’s some code to try out the above classes:
Here’s the output: