Ruby, mixin instance variables and methods

I have two files: one with the ToMix module:

 module ToMix @module_var = "modulevar" def self.mix_function puts "mix_function SELF: #{@module_var}" end def mix_function puts "mix_function: #{@module_var}" end class MixClass attr_accessor :mixclassvar def initialize(value) @mixclassvar = value end end end 

which I want to mix with the TestInclude class in another file:

 class TestInclude require "ToMixFile" include ToMix end 

Can anyone explain why the @module_var instance @module_var and the self.mix_function , mix_function are undefined? And how would I define them?

 t2 = TestInclude.new() t2.mix_function # => error undefined (exected call to mix_function) t2.module_var = "test set module_var" # => error undefined TestInclude.mix_function # => error undefined (expected call to self.mix_function) TestInclude.method_defined? :mix_function # => false 
+4
source share
1 answer

Modules add functions to things; attr_accessor adds functions for interacting with a variable.

 module ToMix @module_var = "module_var" attr_accessor :mixed_var def initialize @mixed_var = "mixed_var" end def mix_function puts "mix_function: #{@mixed_var}" end def self.module_function @module_var end end class Mixed include ToMix end Mixed.new.mixed_var 

It should be noted that

 "".extend(ToMix).mixed_var == nil # no error, but no value, interesting! 

but

 (a = "".extend(ToMix)).mixed_var = "interesting" a.mixed_var == "interesting" 

and

 ToMix.module_function == "module_var" 

fooobar.com/questions/19278 / ... http://www.natontesting.com/2009/09/28/accessing-instance-variables-declared-in-ruby-modules/ How to dynamically change inheritance in Ruby

Edit: those who are wiser than I have to correct me if I am wrong, but the definitions of modules and classes themselves are objects. Thus, the @var definition in the module definition adds var to the module object itself

Edit: those who wiser corrected me: although class and module definitions behave as a singleton, they themselves are not objects. You can think of def self.bacon and @var outside of methods as static methods and C ++ variables, but they can / only / be available as static even if you are in an instance.

+3
source

Source: https://habr.com/ru/post/1483917/


All Articles