What is mattr_accessor in a Rails module?

后端 未结 2 609
面向向阳花
面向向阳花 2020-12-22 17:05

I couldn\'t really find this in Rails documentation but it seems like \'mattr_accessor\' is the Module corollary for \'attr_accesso

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-22 17:18

    Here's the source for cattr_accessor

    And

    Here's the source for mattr_accessor

    As you can see, they're pretty much identical.

    As to why there are two different versions? Sometimes you want to write cattr_accessor in a module, so you can use it for configuration info like Avdi mentions.
    However, cattr_accessor doesn't work in a module, so they more or less copied the code over to work for modules also.

    Additionally, sometimes you might want to write a class method in a module, such that whenever any class includes the module, it gets that class method as well as all the instance methods. mattr_accessor also lets you do this.

    However, in the second scenario, it's behaviour is pretty strange. Observe the following code, particularly note the @@mattr_in_module bits

    module MyModule
      mattr_accessor :mattr_in_module
    end
    
    class MyClass
      include MyModule
      def self.get_mattr; @@mattr_in_module; end # directly access the class variable
    end
    
    MyModule.mattr_in_module = 'foo' # set it on the module
    => "foo"
    
    MyClass.get_mattr # get it out of the class
    => "foo"
    
    class SecondClass
      include MyModule
      def self.get_mattr; @@mattr_in_module; end # again directly access the class variable in a different class
    end
    
    SecondClass.get_mattr # get it out of the OTHER class
    => "foo"
    

提交回复
热议问题