!Electronic || !Bionic || !Ultrasonic

Following the article Keyword With I present here how I write a Module to be included an a class. It has to extend the class with class methods and instance methods.


Note that in the spirit of ruby there are more way of doing this. The amount of possibility can be overwhelming for newcomers that are used to stricter languages.

Even experienced developers needs some time to get used to it. But there is the freedom to define our own behavior.

Some Module

When writing a library I prefer to implement a mixin that adds the desired capabilities to a class instead of polymorphism. So the end developer is free to
use the class inheritance mechanism to build the solution to his problem.

	module Foo
		def self.included(base)
 
			#add class methods
			with base.meta_class do
				include ClassMethods
			end
 
			#add instance methods
			with base do
				include InstanceMethods
			end
		end
 
		module ClassMethods
			# class definitions goes here
			def foo
				puts "I am a class method"
			end
		end
 
		module InstanceMethods
			attr_accessor :title
 
			# instance definitions goes here
			def foo
				puts "I am a instance method"
			end
		end

This module should be used as follow:

	class A
		include Foo
	end
 
	A.foo => "I am a class method"
	a = A.new
	a.foo => "I am a instance method"
	a.title = "Hello World"
Related posts:
  1. Ruby Inox Part 3.1: Actions Here is a short update for the Ruby Inox Part3:...
  2. Ruby Inox Part 5: Component Something promised is something due. Only two days have passed...
  3. Aspect the Ruby way The main purpose of this file is to be able...
  4. Keyword With From other programming language I know a interesting feature; the...
  5. Ruby Inox Part 3: Actions Here is the pursuit of a series of related articles...
  6. Ruby Inox Part 4.1: Property In Ruby Inox Part 4: Property I described I would...
Email Icon Facebook Icon Twitter Icon Share this IconShareThis Follow Ironicwolf on Twitter