I have a Module with a constant and variable.
I wonder how I could include these in a class?
module Software
VAR = 'hejsan'
def exit
@text = "exited"
puts @text
end
end
class Windows
extend Software
def self.start
exit
puts VAR
puts @text
end
end
Windows.start
Is this possible?
Ruby 1.9.3:
module Software
VAR = 'hejsan'
module ClassMethods
def exit
@text = "exited"
puts @text
end
end
module InstanceMethods
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
class Windows
include Software
def self.start
exit
puts VAR
puts @text
end
end
Windows.start
In IRB:
exited
hejsan
exited
Doing exactly what you want is not possible. Instance variables are strictly per object.
This happens to do what you expect, but @text
is set on Windows
not Software
.
module Software
VAR = 'hejsan'
def exit
@text = "exited"
puts @text
end
end
class Windows
class <<self
include Software
def start
exit
puts VAR
puts @text
end
end
end
Windows.start
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With