I will add my five kopecks. In the module, you can reload the included method, which is executed each time the module is included in another module or class using the include statement. As an argument, the class is passed to the method where the module was mixed in, which allows you to define your own methods:
module Library module Commentable def self.included(base) base.class_eval do def comments= comments @comments = comments end def comments @comments end end end end end class Library::Book include Library::Commentable attr_accessor :author, :title def initialize author, title @author = author @title = title end end o = Library::Book.new 'Мария Эрих Ремарк', 'Три товарища' o.comments = [] p o.comments
However, as already mentioned D-side, a much more elegant task can be solved using the prepend method, which allows you to solve the problem more elegantly.
module Library module Commentable attr_accessor :comments def initialize author, title @author = author @title = title @comments = [] end end end class Library::Book prepend Library::Commentable attr_accessor :author, :title def initialize author, title @author = author @title = title end end o = Library::Book.new 'Мария Эрих Ремарк', 'Три товарища' p o.comments p o.author
In the last example, you overwrite the Library::Book#initialize method with the Library::Commentable#initialize method. It doesn't make any sense here - since the example is very compact, but if you need to change the behavior of a class somewhere on the fly, you can open it and fix it with your module.
class Library::Book prepend Library::Commentable end