Ruby, mixin instance variables and methods

自古美人都是妖i 提交于 2020-01-02 06:09:45

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/16869832/ruby-mixin-instance-variables-and-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!