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

实例公共方法

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 85
  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

      class_methods << <<~RUBY # In case the method exists and is not public
        silence_redefinition_of_method def #{name}
        end
      RUBY

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

      class_methods << <<~RUBY
        silence_redefinition_of_method def #{name}=(value)
          redefine_method(:#{name}) { value } if singleton_class?
          redefine_singleton_method(:#{name}) { value }
          value
        end
      RUBY

      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)

    attrs.each { |name| public_send("#{name}=", default) }
  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 21
def descendants
  subclasses.concat(subclasses.flat_map(&:descendants))
end

subclasses()

返回一个包含 self 的直接子类的数组。

class Foo; end
class Bar < Foo; end
class Baz < Bar; end

Foo.subclasses # => [Bar]
# File activesupport/lib/active_support/core_ext/class/subclasses.rb, line 38
def subclasses
  descendants.select { |descendant| descendant.superclass == self }
end