Ruby: klasa C zawiera moduł M; w tym moduł N w M nie wpływa na C. Co daje?
Bardziej dosłownie mam modułNarf
, który zapewnia podstawowe funkcje dla szeregu klas. W szczególności chcę wpływać na wszystkie klasy, które dziedzicząEnumerable
. Więc jainclude Narf
wEnumerable
.
Array
to klasa, która zawieraEnumerable
domyślnie. Jednak nie ma na nią wpływu późne włączenieNarf
w module.
Co ciekawe, klasy zostały zdefiniowane po włączeniuNarf
zEnumerable
.
# This module provides essential features
module Narf
def narf?
puts "(from #{self.class}) ZORT!"
end
end
# I want all Enumerables to be able to Narf
module Enumerable
include Narf
end
# Fjord is an Enumerable defined *after* including Narf in Enumerable
class Fjord
include Enumerable
end
p Enumerable.ancestors # Notice that Narf *is* there
p Fjord.ancestors # Notice that Narf *is* here too
p Array.ancestors # But, grr, not here
# => [Enumerable, Narf]
# => [Fjord, Enumerable, Narf, Object, Kernel]
# => [Array, Enumerable, Object, Kernel]
Fjord.new.narf? # And this will print fine
Array.new.narf? # And this one will raise
# => (from Fjord) ZORT!
# => NoMethodError: undefined method `narf?' for []:Array