Skip to content

Instantly share code, notes, and snippets.

@mfdeveloper
Last active May 6, 2019 01:51
Show Gist options
  • Save mfdeveloper/452439784c3367967df2 to your computer and use it in GitHub Desktop.
Save mfdeveloper/452439784c3367967df2 to your computer and use it in GitHub Desktop.
Ruby Modules

Ruby Modules

Here you will find examples of modules in ruby code. The structure is strong, very important and commonly used by ruby developers! Modules can be used like namespaces or mixins (adds new methods to a class).

Namespaces

In ruby code it's common see something like this:

MyModule::MyClass

The character :: is a namespace separator. A dot '.' can be used to, but it's not recommended.

Mixins

Add new features (methods and properties) to a class that use include or extend keyword followed by the module name.

# First example: Modules like a Namespaces
#
# This first example of 'modules' shows
# a use of its like a namespace
module MyNamespace
CONSTANT_TEST = 'value'
# This class can be accessed by '::'
# or '.' sinal. Prefer always '::' sinal
class MyInnerClass
def inner_method
puts 'This is a internal method'
end
end
end
obj_namespace = MyNamespace::MyInnerClass.new
obj_namespace.inner_method
# Second example: Modules like a Mixins.
#
# This second example, shows the use of modules
# like a 'mixin', adding methods to a class that
# call 'include' method.
#
module MyMixin
# This method will be added in a class
# that included them, like a 'inheritance'.
def object_method
puts 'This is a object method added by "include" in a class'
end
end
class MyClass
# Includes the module and add
# yours object methods.
#
# You can use too the 'Object.extend' to add
# methods of module in only one specific object.
include MyMixin
end
obj_mixin = MyClass.new
obj_mixin.object_method
# Third example: using 'extend' method
# for include methods of a module.
class AnotherClass
# The 'extend' method add methods of
# 'MyMixin' module in this class, not in your
# instances like a 'include' method
# in the example above.
extend MyMixin
end
AnotherClass.object_method
# Fourth example: Create a module named 'ClassMethods'
# to include methods by 'included' module callback
# implementation.
#
# Obs: Rails framework create the module 'ClassMethods'
# to do this by default.
module ClassMethods
def class_method
puts 'This is a method of a class included by "ClassMethods" module'
end
end
module AnotherModule
# The hook called when 'include' method
# is invoked in some class
def self.included(base)
base.extend(ClassMethods)
end
end
class MyHookedClass
include AnotherModule
end
MyHookedClass.class_method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment