I'm pretty new to Ruby and seems that I'm still confused with mixin and including modules in classes. I would like to be able to access instance variables (@) defined in modules in classes. I have the following piece of code:
module ModuleB
attr_reader :b
def ModuleB.initialize(browser)
puts "initialize from ModuleB"
@browser = browser
@b = 5
end
end
module ModuleA
attr_reader :a
include ModuleB
def ModuleA.initialize(browser)
ModuleB.initialize(browser)
puts "initialize from ModuleA"
@browser = browser
@a = @b
end
def action_1
@a = @b + 1
return @a
end
end
class ClassA
include ModuleA
def initialize(browser)
ModuleA.initialize(browser)
@browser = browser
puts 'initialize - method in ClassA'
@c = @a
@d = @b
puts "a = #{@a}"
puts "b = #{@b}"
puts "c = #{@c}"
puts "d = #{@d}"
end
end
s = 'hello'
instA = ClassA.new(s)
puts instA.action_1
And here's the output that I get:
initialize from ModuleB
initialize from ModuleA
initialize - method in ClassA
a =
b =
c =
d =
mixin_example2.rb:23:in `action_1': undefined method `+' for nil:NilClass (NoMethodError)
from mixin_example2.rb:46:in `<main>'
Seems like @a and @b are uninitialized.
Additional thing, is that I cannot use '+' operator in action_1 method.
What did I miss?
Sorry if I repeated problem that might have already been raised but I didn't find an answer so far.
includesimply creates a class and makes that class the superclass.