A continuación se desglosaran tres ejemplos de Mixin en Ruby:
Mixin dentro de una clase:
module ModuleExample def to_s return "uno" if @number == 1 return "dos" if @number == 2 return "tres" if @number == 3 return "mucho" end end class ClassExample include ModuleExample #Utilizamos el include dentro de la clase attr_accessor :number end objectExample = ClassExample.new objectExample.number = 3 puts"#{objectExample.to_s}" #tres objectExample2 = ClassExample.new objectExample2.number = 2 puts"#{objectExample2.to_s}" #dos
Mixin en una instancia:
module ModuleExample def to_s return "uno" if @number == 1 return "dos" if @number == 2 return "tres" if @number == 3 return "mucho" end end class ClassExample attr_accessor :number def to_s @number.to_s end end objectExample = ClassExample.new objectExample.extend(ModuleExample) #Solo este objecto hereda los métodos del modulo objectExample.number = 3 puts"#{objectExample.to_s}" #tres objectExample2 = ClassExample.new objectExample2.number = 2 puts"#{objectExample2.to_s}" #2
¿?
module ModuleExample def methodExample puts "Hey" end end class ClassExample extend(ModuleExample) #extend en vez de include end ClassExample.methodExample # 'Hey' objectExample = ClassExample.new # objectExample.methodExample # Error. No se puede llamar al metodo