Created
March 20, 2014 09:01
-
-
Save malpinder/9659868 to your computer and use it in GitHub Desktop.
Modules cheatsheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Modules can be used for namespacing... | |
module Whizz | |
class SoundEffect | |
def noise | |
"Whizzo!" | |
end | |
end | |
class Popper | |
def make_noise | |
# Don't need to specify namespace when you are inside it. | |
puts SoundEffect.new.noise | |
end | |
end | |
end | |
# Do need to specify namespace when you are outside it. | |
# Separate each level of spacing with :: | |
Whizz::Popper.new.make_noise | |
# And modules can be used to move shared functionality into one place. | |
module PowersOfArrest | |
def can_arrest_people? | |
true | |
end | |
end | |
class PoliceOfficer | |
# include makes all methods in the module instance methods on the class. | |
include PowersOfArrest | |
# This is like writing: | |
# def can_arrest_people? | |
# true | |
# end | |
end | |
puts PoliceOfficer.new.can_arrest_people? | |
class Robocop | |
# extend makes all methods in the module class methods. | |
extend PowersOfArrest | |
# This is like writing: | |
# def self.can_arrest_people? | |
# true | |
# end | |
end | |
puts Robocop.can_arrest_people? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment