What is mattr_accessor in a Rails module?

后端 未结 2 607
面向向阳花
面向向阳花 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:17

    Rails extends Ruby with both mattr_accessor (Module accessor) and cattr_accessor (as well as _reader/_writer versions). As Ruby's attr_accessor generates getter/setter methods for instances, cattr/mattr_accessor provide getter/setter methods at the class or module level. Thus:

    module Config
      mattr_accessor :hostname
      mattr_accessor :admin_email
    end
    

    is short for:

    module Config
      def self.hostname
        @hostname
      end
      def self.hostname=(hostname)
        @hostname = hostname
      end
      def self.admin_email
        @admin_email
      end
      def self.admin_email=(admin_email)
        @admin_email = admin_email
      end
    end
    

    Both versions allow you to access the module-level variables like so:

    >> Config.hostname = "example.com"
    >> Config.admin_email = "admin@example.com"
    >> Config.hostname # => "example.com"
    >> Config.admin_email # => "admin@example.com"
    

提交回复
热议问题