跳至内容 跳至搜索
方法
C
D

实例公共方法

class_attribute(*attrs, instance_accessor: true, instance_reader: instance_accessor, instance_writer: instance_accessor, instance_predicate: true, default: nil)

声明一个类级属性,其值可被子类继承。子类可以更改它们自己的值,这不会影响父类。

选项

  • :instance_reader - 设置实例读取器方法(默认为 true)。

  • :instance_writer - 设置实例写入器方法(默认为 true)。

  • :instance_accessor - 设置两个实例方法(默认为 true)。

  • :instance_predicate - 设置一个谓词方法(默认为 true)。

  • :default - 为属性设置一个默认值(默认为 nil)。

示例

class Base
  class_attribute :setting
end

class Subclass < Base
end

Base.setting = true
Subclass.setting            # => true
Subclass.setting = false
Subclass.setting            # => false
Base.setting                # => true

在上述情况下,只要子类没有通过执行Subclass.setting = something为设置分配值,Subclass.setting就会读取分配给父类的值。一旦子类分配了一个值,那么子类分配的值就会被返回。

这与正常的 Ruby 方法继承相匹配:将属性写入子类就像覆盖读取器方法。但是,在将class_attribute与可变结构(如ArrayHash)一起使用时,需要意识到这一点。在这种情况下,您不希望在适当的位置进行更改。而是使用设置器

Base.setting = []
Base.setting                # => []
Subclass.setting            # => []

# Appending in child changes both parent and child because it is the same object:
Subclass.setting << :foo
Base.setting               # => [:foo]
Subclass.setting           # => [:foo]

# Use setters to not propagate changes:
Base.setting = []
Subclass.setting += [:foo]
Base.setting               # => []
Subclass.setting           # => [:foo]

为了方便起见,还定义了一个实例谓词方法。要跳过它,请传递instance_predicate: false

Subclass.setting?       # => false

实例可以以相同的方式覆盖类值

Base.setting = true
object = Base.new
object.setting          # => true
object.setting = false
object.setting          # => false
Base.setting            # => true

要选择不使用实例读取器方法,请传递instance_reader: false

object.setting          # => NoMethodError
object.setting?         # => NoMethodError

要选择不使用实例写入器方法,请传递instance_writer: false

object.setting = false  # => NoMethodError

要选择不使用两个实例方法,请传递instance_accessor: false

要为属性设置默认值,请传递default:,如下所示

class_attribute :settings, default: {}
# File activesupport/lib/active_support/core_ext/class/attribute.rb, line 86
  def class_attribute(*attrs, instance_accessor: true,
    instance_reader: instance_accessor, instance_writer: instance_accessor, instance_predicate: true, default: nil)

    class_methods, methods = [], []
    attrs.each do |name|
      unless name.is_a?(Symbol) || name.is_a?(String)
        raise TypeError, "#{name.inspect} is not a symbol nor a string"
      end

      name = name.to_sym
      ::ActiveSupport::ClassAttribute.redefine(self, name, default)

      unless singleton_class?
        methods << <<~RUBY if instance_reader
          silence_redefinition_of_method def #{name}
            defined?(@#{name}) ? @#{name} : self.class.#{name}
          end
        RUBY
      end

      methods << <<~RUBY if instance_writer
        silence_redefinition_of_method(:#{name}=)
        attr_writer :#{name}
      RUBY

      if instance_predicate
        class_methods << "silence_redefinition_of_method def #{name}?; !!self.#{name}; end"
        if instance_reader
          methods << "silence_redefinition_of_method def #{name}?; !!self.#{name}; end"
        end
      end
    end

    location = caller_locations(1, 1).first
    class_eval(["class << self", *class_methods, "end", *methods].join(";").tr("\n", ";"), location.path, location.lineno)
  end

descendants()

返回一个包含所有小于其接收者的类的数组。

class C; end
C.descendants # => []

class B < C; end
C.descendants # => [B]

class A < B; end
C.descendants # => [B, A]

class D < C; end
C.descendants # => [B, A, D]
# File activesupport/lib/active_support/core_ext/class/subclasses.rb, line 19
def descendants
  subclasses.concat(subclasses.flat_map(&:descendants))
end