The Basics of Creating and Using Ruby Modules

Ruby on Rails is a wonderful open source full-stack web application framework favoring convention over configuration.  Con componentes reutilizables y fácilmente configurables que normalmente se utilizan para crear aplicaciones, crear aplicaciones en Rails es más rápido y sencillo, lo que se traduce en una mayor productividad y crecimiento empresarial. Está ganando terreno entre los desarrolladores, ya que es flexible, escalable y fácil para los desarrolladores web escribir y mantener aplicaciones. 

Ruby on Rails Pone énfasis en el uso de patrones y principios de ingeniería conocidos para reducir la carga de trabajo al crear aplicaciones web. Aunque existen múltiples métodos para resolver un desafío de programación, Ruby profesa confiar en patrones comúnmente utilizados que hacen que los sitios web Rails sean más fáciles de mantener y actualizar. Las bibliotecas de código abierto con bloques más pequeños de código Rails que resuelven problemas particulares se utilizan comúnmente para reducir la sobrecarga de desarrollo. Con la ayuda de dichos bloques de código, los desarrolladores pueden insertar gemas estables y bien probadas en lugar de perder tiempo escribiendo el mismo tipo de códigos. Una de las herramientas más poderosas en la caja de herramientas de un programador Ruby es el módulo. Rubí Modules provide a structure to collect Ruby classes, methods, and constants into a single, separately named and defined unit.

Esto es útil para evitar conflictos con clases, métodos y constantes existentes, y también para poder agregar (mezclar) la funcionalidad de los módulos en sus clases.

Creating a Module in Ruby

Creating a module is similar to creating a class, except you use the module keyword instead of the class keyword.

module MyFirstModule
  def say_hello
    puts "Hello"
  end
end

Modules cannot be instantiated. To use a module, you must either include or extend it within a class.

Using include and extend

  • incluir

Mixes the module’s methods in as instance methods of the class.

  • ampliar

Mixes the module’s methods in as class methods of the class.

Example

module ReusableModule
  def module_method
    puts "Module Method: Hi there!"
  end
end

class ClassThatIncludes
  include ReusableModule
end

class ClassThatExtends
  extend ReusableModule
end

puts "Include"
ClassThatIncludes.new.module_method
# => "Module Method: Hi there!"

puts "Extend"
ClassThatExtends.module_method
# => "Module Method: Hi there!"

Other Important Concepts About Modules in Ruby

1. Method Lookup Basics:

module M
  def report
    puts "'report' method in module M"
  end
end

class C
  include M
end

class D < C
end
obj = D.new obj.report

Producción:

'report' method in module M

How Method Lookup Works

When a Ruby object receives a message (method call), it searches for the method in this order:

  1. The objects class (D)
  2. Modules included in the class (D)
  3. The superclass (C)
  4. Modules included in the superclass (M)
  5. Continue up the inheritance chain

In this case:

  • D does not define report
  • C does not define report
  • C includes module M
  • M defines report, so Ruby executes it

2. Defining the Same Method More Than Once

If a method is defined multiple times, the last definition takes precedence. This applies to both classes and modules.

module InterestBearing
  def calculate_interest
    puts "Placeholder! We're in module InterestBearing."
  end
end

class BankAccount
  include InterestBearing

  def calculate_interest
    puts "Placeholder! We're in class BankAccount."
    puts "And we're overriding the calculate_interest method!"
  end
end

account = BankAccount.new
account.calculate_interest

Producción:

Placeholder! We're in class BankAccount.
And we're overriding the calculate_interest method!

The class method overrides the module method.

3. Mixing in Multiple Ruby Modules with the Same Method Name

module M
  def report
    puts "'report' method in module M"
  end
end

module N
  def report
    puts "'report' method in module N"
  end
end

class C
  include M
  include N
end

c = C.new
c.report

Producción:

'report' method in module N

The last included module wins because it appears first in the method lookup path.

4. Including a Ruby Module More Than Once

class C
  include M
  include N
  include M
end

c = C.new
c.report

Producción:

'report' method in module N

Explanation

Re-including a module has no effect if the module is already in the lookup path. Ruby does not move it to the top again. The most recently included new module (N) still takes precedence.

5. Using super with Ruby Modules

The super keyword allows you to call the next method up the method lookup chain.

module M
  def report
    puts "'report' method in module M"
  end
end

class C
  include M

  def report
    puts "'report' method in class C"
    puts "About to trigger the next higher-up report method..."
    super
    puts "Back from the 'super' call."
  end
end

c = C.new
c.report

Producción:

'report' method in class C
About to trigger the next higher-up report method...
'report' method in module M
Back from the 'super' call.

What Happens Here

  • Ruby first executes report in class C
  • super calls the next report method in the lookup chain (from module M)
  • Control then returns back to the class method

RielesCarma ha estado trabajando en RoR desde su etapa inicial y con una sólida fuerza laboral capacitada en RoR, ha crecido hasta convertirse en un nombre altamente confiable en consultoría, arquitectura, construcción, administración y extensión de Ruby on Rails para empresas de todo el mundo. 

Leer más : 

Póngase en contacto con nosotros.

Suscríbete para recibir las últimas actualizaciones

Artículos Relacionados

Acerca del autor de la publicación

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *


es_ESSpanish