This guide walks through how to integrate Ruby modules in order to add custom helper methods to a class.
Build a module with helper methods and call the methods from a class.
Build a helper module called
InvoiceHelper that contains a method called
taxable? that checks the source of an order and returns if it’s taxable order or not. Then build a class called
Sale that has a
source attribute. Then build a method called
place_order that returns the total plus a 6% tax rate if the source is
online, and returns the total by itself if the source is any other value.
s = Sale.new(500, 'AZ') s.place_order # => 530.0 s2 = Sale.new(500, 'TX') s2.place_order # => 500.0
Real World Usage
Building helper modules is an important task when it comes to code organization. This example is a practical case study on how you can add a boolean helper method to a class without having to clutter the class code.
Can be found on the solutions branch on github.