working as expected
class Foo
@@x = 12
def self.bar
p @@x
end
end
class Bar < Foo
end
Bar.bar # => 12
I am having some hard time to understand why the below code is not
working, while the above.
module Foo
@@x = 12
def self.bar
p @@x
end
end
class Bar
include Foo
end
Bar.bar # undefined method bar’ for Bar:Class (NoMethodError)
Hi.
Basically, when you include a module, you make the module’s methods
available to objects of the resulting class. A class-level or
module-level method must be used on the class or module directly. As you
do not “inherit” from a module but either include it or extend an object
with it, you should not expect the class Bar to react as if it had
inherited from any other class.
Also, you do not create a singleton in your example-code.
sing = Bar.new.extend(Foo)
- creates a singleton ‘sing’
What you want is this:
lose self
module Foo
def bar
p 12
end
end
extend the class directly
class Bar
extend Foo
end
- extends the class Bar with the module Foo. Try that instead. You will
be surprised…
Cheerio.
P.S.: I do not like metaprogramming. Modules, to me, are a way to create
“Polymorphism” in Ruby.