module
http://lizabinante.com/blog/modules-and-self-in-ruby/
Module Mixin
extend
vs. include
in classes
extend
vs. include
in classesinclude
: instance methodsextend
: class methods
module Animals
def mammals
["sloths", "puppies", "porcupines"]
end
end
# - - - - - - - - include
class Zoo
include Animals
end
zoo = Zoo.new
zoo.mammals # => ["sloths", "puppies", "porcupines"]
zoo.methods - Object.methods # => mammals
# - - - - - - - - extend
class PetStore
extend Animals
end
PetStore.mammals # => ["sloths", "puppies", "porcupines"]
pet_store = PetStore.new
pet_store.mammals # => undefined method `mammals' for #<PetStore:0x007f858a919f30> (NoMethodError)
PetStore.methods - Object.methods # => mammals
pet_store = PetStore.new
pet_store.methods - Object.methods # =>
Module Methods
extend self
:
Not change the behavior of include or extend in your classes
self
method name prefix
change the behavior of include or extend in your classes (
self
prefix can not be mixed in)only access some of methods in module (access
self
prefix only)
extend self
extend self
module Animals
extend self
def mammals
["sloths", "puppies", "porcupines"]
end
def sea_creatures
["narwhal", "starfish", "dolphin"]
end
end
Animals.mammals # => ["sloths", "puppies", "porcupines"]
Animals.sea_creatures # => ["narwhal", "starfish", "dolphin"]
# - - - - - - - - include
class Zoo
include Animals
end
Zoo.mammals # => undefined method `mammals' for Zoo:Class (NoMethodError)
zoo = Zoo.new
zoo.mammals # => ["sloths", "puppies", "porcupines"]
# - - - - - - - - extend
class PetStore
extend Animals
end
PetStore.mammals # => ["sloths", "puppies", "porcupines"]
pet_store = PetStore.new
pet_store.mammals # => undefined method `mammals' for #<PetStore:0x007f858a919f30> (NoMethodError)
self
method name prefix
self
method name prefixmodule Animals
def self.mammals
["sloths", "puppies", "porcupines"]
end
def sea_creatures
["narwhal", "starfish", "dolphin"]
end
end
Animals.mammals # => ["sloths", "puppies", "porcupines"]
Animals.sea_creatures # => undefined method
# - - - - - - - - include
class Zoo
include Animals
end
Zoo.mammals # => undefined method
Zoo.sea_creatures # => undefined method
zoo = Zoo.new
zoo.mammals # => undefined method
zoo.sea_creatures # => ["narwhal", "starfish", "dolphin"]
# - - - - - - - - extend
class PetStore
extend Animals
end
PetStore.mammals # => undefined method
PetStore.sea_creatures # => ["narwhal", "starfish", "dolphin"]
pet_store = PetStore.new
pet_store.mammals # => undefined method
pet_store.sea_creatures # => undefined method
Last updated
Was this helpful?