Skip to content

Instantly share code, notes, and snippets.

@yangsu
Last active December 11, 2015 20:09
Show Gist options
  • Save yangsu/4652955 to your computer and use it in GitHub Desktop.
Save yangsu/4652955 to your computer and use it in GitHub Desktop.
Ruby Module Example
module Person
attr_accessor :name
def self.included(base) # included is invoked whenever a module is included; base is implicit
base.extend ClassMethods # extend will add the methods defined in ClassMethods as class methods
end
module ClassMethods
def can_speak
include InstanceMethods # This includes all the instance methods
end
end
module InstanceMethods
def speak
puts "I can talk, my name is #{@name}!"
end
end
def initialize(name)
@name = name
end
end
class Guy
include Person
can_speak
end
class ShyGuy
include Person
end
john = Guy.new('John')
bob = ShyGuy.new('Bob')
john.methods.include?(:speak) # true
bob.methods.include?(:speak) # false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment