Modules and Gems
Clone or download
Pull request Compare This branch is even with wdi-nyc-delorean:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
README.md

README.md

Modules and Gems

Modules

Modules play two roles in Ruby: organization and mixins

Organization

Modules can act like a namespace to keep the different parts of a library organized and spread out across separate files.

# version.rb
module DeLorean
  VERSION = "1.0.0"
end
# functions.rb
module DeLorean
  def DeLorean.cool?
    true
  end
end
# student.rb
module DeLorean
  class Student
    def hello
      puts "hi hello"
    end
  end
end
# delorean.rb

require "version"
require "functions"
require "student"

You can access the whole library with require "delorean" and the the DeLorean module is available in the global scope. You access methods with . and constants with ::, e.g. DeLorean.cool? and DeLorean::VERSION and DeLorean::Student.

Lab

Add an am_i_cool? method to the Student class in a separate file that uses the DeLorean.cool? method.

Mixins

Module methods can be "mixed in" to a class using include. The class gets all the instance methods defined in the module.

module Superpowers
  def fly
    @flying = true
    puts "flying away!"
  end

  def flying?
    @flying
  end

  def land
    @flying = false
    puts "back on the ground"
  end
end

class Human

end

h = Human.new
h.fly
# NoMethodError: undefined method `fly' for #<Human:0x007fbe2589c390>

class Human
  include Superpowers
  # ...
end

h = Human.new
h.fly
# "flying away!"

Modules have access to the classes variables and methods. The ruby standard library provides powerful mixins for your code like, Enumerable and Comperable.

Lab

  1. Create a Human class with a name property
  2. Create an Invisible module with methods become_invisible and invisible? and become_visible
  3. Create a LaserEyes module with the method zap!
  4. Create another module with your own super power
  5. Create subclasses of Human that mixin different superpower modules to create different super heroes

Gems

Where Node used packages and npm, Ruby uses gems and bundler. Instead of a package.json, we create and maintain a Gemfile. Instead of a node_modules folder, the gems get installed to a global location, but bundler generally takes care of that for us.

Lab

Write a Gemfile using at least three gems from https://github.com/markets/awesome-ruby and write a basic Ruby script that uses them.