简体   繁体   English

如何从Ruby的父代包含模块继承类变量

[英]How to inherit class variables from parents included module in Ruby

I am trying to develop a reusable module for Active Record models to be used shared in models. 我正在尝试为Active Record模型开发可重用的模块,以在模型中共享使用。 It works well except child classes can't find the variables. 除子类找不到变量外,它工作得很好。

This is easier demonstrated with code 用代码更容易证明

This is the module: 这是模块:

module Scanner
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def scan(*fields)
      @scan = fields if fields.present?
      @scan
    end
  end
end

Usage: 用法:

class User < ActiveRecord::Base
  include Scanner
  scan :user_name
end

Calling User.scan returns :user_name . 调用User.scan返回:user_name Perfect! 完善!

However. 然而。 This is an issue: 这是一个问题:

class Admin < User
end

Calling Admin.scan returns nil 调用Admin.scan返回nil

How come :user_name is not being set in the parent? 为何未在父级中设置:user_name I am following the source for AR for methods like primary_key and table_name , they seem to be inherting values from the parent 我正在跟踪AR的源代码,例如primary_keytable_name方法,它们似乎是从父级继承值

class_attribute takes care of the required inheritance semantics for you. class_attribute为您处理所需的继承语义。 As you've seen, it's not quite as simple as putting an instance variable on the class, because that leaves it nil on subclasses: they're instance variables, and that's a separate instance. 如您所见,这并不像将实例变量放在类上那样简单,因为这使子类上的实例变量nil :它们是实例变量,并且是一个单独的实例。

The examples you mention do other, more specialised and more complicated, things... but you'll find plenty of straightforward examples in the Rails source that do use class_attribute . 您提到的示例还有其他一些更专业,更复杂的事情……但是,您会在Rails源代码中找到许多直接使用class_attribute的简单示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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