Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Lowdown on Ruby Modules

Lowdown on Ruby Modules

Modules are wonderfully flexible language constructs which can be applied to a wide variety of use cases, such as namespacing, inheritance, and decorating. However, some developers are still confused about how modules work and how they interact with their own code. These slides aims to shed some light on Modules and their usage.

Presentation made from - https://www.sitepoint.com/get-the-low-down-on-ruby-modules/

Varun Lalan

July 23, 2016
Tweet

Other Decks in Programming

Transcript

  1. What we will see? • What are Modules? • Ruby

    Object Model (ROM) • Method Lookup • Using Modules
  2. What are Modules? • A way of grouping together methods,

    classes, and constants. • Namespacing • Inheritance
  3. Modules • Modules are wonderfully flexible language constructs. • Understanding

    how Modules fit in Ruby Object Model is essential to use them fully and creatively.
  4. The Ruby Object Model - ROM • Classes (class-objects) •

    Class Instances (instance-objects) • Modules
  5. The Ruby Object Model - ROM class Car def drive

    "Vroooom" end end class Ferrari < Car end
  6. The Ruby Object Model - ROM > my_car = Car.new

    Ruby will create object’s eigenclass directly under our Car class. It will place our new instance (my_car) to the left of its eigenclass and outside the object hierarchy.
  7. Method Lookup > my_car.drive The object we call a method

    on (my_car) is called the receiver object.
  8. Modules in Their Environment There are three things we can

    do with a module: • Include it in our class-objects • Prepend it to our class-objects • Extend our class objects or instance objects with it
  9. Modules in Their Environment • Including a module in our

    object will place it directly above our object. • Prepending a module to our object will place it directly below our object. • Extending our object with a module will place it directly above our object’s eigenclass.
  10. “ Modules aren’t technically Classes, `superclass ` won’t show us

    any modules directly above our class. For that, we need to use the `ancestors ` method.
  11. “ If we define a method with the same name

    in our Car class, Ruby will find and run this instead and our Module method will never be called.
  12. Prepending Modules module ElectricEngine def drive; "eco-driving!"; end end class

    Car prepend ElectricEngine def driver; "driving"; end end my_car = Car.new my_car.drive => eco-driving!