In my recent pursue of learning Rails, I have gotten more exposure to the Ruby. The Ruby programming language is very pretty in terms of its syntax and the semantics. It is object-oriented and allow classes to import modules as mixins, which is the subject of this post.
I am still very new to Ruby and pretty much learning as I go along. This post is more to document my own learning than anything.
module MySharedModule
HASH_CONSTANT = {:mykey => "value of mykey"}
def mixin_method
puts "calling mixin method"
end
class ClassInModule
def self.class_method
puts "calling class method"
end
def instance_method
puts "calling instance_method"
end
end
end
class MyClass
include MySharedModule
def initialize
# access module's constant
# to be more verbose: MySharedModule::HASH_CONSTANT
puts HASH_CONSTANT[:mykey]
# access module method
mixin_method
# calls class method of a class in module
# to be more verbose: MySharedModule::ClassInModule.class_method
ClassInModule.class_method
# instantiate, call instance method of class in module
# to be more verbose: MySharedModule::ClassInModule.class_method
instance = ClassInModule.new
instance.instance_method
end
end
myClass = MyClass.new
# Output:
# value of mykey
# calling mixin method
# calling class method
# calling instance_method
To learn more about using modules in Ruby: