Hello,
Recently a colleague and I discovered that our understanding of how
modules work, with regards to reopening a module after being included
in a class, seems to be at odds with how Ruby actually handles the
situation.
I am providing an example of code that highlights the situation.
What do you think will happen?
My expectations are given after the code.
···
------------------------------
module LangDefault
def foo
:LangDefault
end
end
module XLang
include LangDefault
end
module JLang
def foo
:JLang
end
end
class Talk
include XLang
end
tlk = Talk.new
puts tlk.foo
module XLang
include JLang
end
puts tlk.foo
puts Talk.new.foo
class Write
include XLang
end
puts Write.new.foo
puts Talk.included_modules.join(",")
puts Write.included_modules.join(",")
class Talk
include XLang
end
puts Talk.new.foo
------------------------------
I assumed that once XLang included JLang, after the first time Talk
included XLang, that Talk would also recognize this change. Thus, an
instance of Talk's invocation of foo after XLang included JLang would
return :JLang instead of :LangDefault. This is what an instance of
Write's invocation does. Unfortunately, Talk does not do this until I
include XLang in Talk.
Is this a design decision or an implementation issue?
I ask, because I would like to further refine my understanding of
modules and I am looking for techniques for run time extension of a
program. Currently, the above works except that I have to make sure
that a module is extended before it is included in any classes.
Best,
Zev Blut