Ruby /
Metaprogramming /
Dynamics of Modules
Как и класс, можно создавать модули динамически с помощью Module.new -
Busyness = Module.new do
def self.work
puts "Okay, okay, I'll work"
end
end
Object.const_set("Busyness", new_module_definition)
Busyness.work
# => Okay, okay, I'll work
Можно изменять модуль с помощью метода module_eval -
Busyness.module_eval do
def self.work
puts "Fuck off! I'll not work anymore!"
end
end
Busyness.work
# => Fuck off! I'll not work anymore!
Так же, модуль можно динамически добавить в класс -
module Busyness
def work
puts "Okay, okay, I'll work"
end
end
class Person
end
person = Person.new
person.work
# => undefined method 'work' for an instance of Person (NoMethodError)
# Динамическое добавление модуля
Person.include(Busyness)
person.work
# => Okay, okay, I'll work