简体   繁体   中英

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. 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 . Perfect!

However. This is an issue:

class Admin < User
end

Calling Admin.scan returns nil

How come :user_name is not being set in the parent? I am following the source for AR for methods like primary_key and table_name , they seem to be inherting values from the parent

class_attribute takes care of the required inheritance semantics for you. 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.

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 .

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