简体   繁体   中英

Ruby, mixin instance variables and methods

I have two files, one with module ToMix :

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 mixin to the class TestInclude in the other file:

class TestInclude
    require "ToMixFile"
    include ToMix
end

Could someone explain why the instance variable @module_var and methods 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

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

Notably,

"".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"

https://stackoverflow.com/a/151774/171916 http://www.natontesting.com/2009/09/28/accessing-instance-variables-declared-in-ruby-modules/ How to dynamically alter inheritance in Ruby

Edit: Those wiser than I should correct me if I'm wrong, but module and class definitions are themselves objects. Defining a @var in a module definition thus adds the var to the module object itself

Edit: Those wiser than I have corrected me: While class and module definitions sort of behave like a singleton, they are not themselves objects. You can think of def self.bacon and @var outside of methods as c++ static methods and variables, but they can /only/ be access like a static, even if you're in an instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM