модуль ActiveRecord::Inheritance::ClassMethods
Атрибуты
Установите это значение в true, если это абстрактный класс (см. abstract_class?). Если вы используете наследование с ActiveRecord и не хотите, чтобы дочерние классы использовали предполагаемое имя таблицы STI родительского класса, это значение должно быть true. Например, в данном случае:
class SuperClass < ActiveRecord::Base self.abstract_class = true end class Child < SuperClass self.table_name = 'the_table_i_really_want' end
self.abstract_class = true необходимо для того, чтобы Child<.find,.create, or any Arel method> использовал the_table_i_really_want, а не таблицу под названием super_classes
Открытые методы экземпляров
Возвращает значение true, если этот класс является абстрактным, и false в противном случае.
# File activerecord/lib/active_record/inheritance.rb, line 99 def abstract_class? defined?(@abstract_class) && @abstract_class == true end
Возвращает класс, непосредственно наследуемый от ActiveRecord::Base, или абстрактный класс, если таковой имеется, в иерархии наследования.
Если A расширяет AR::Base, A.base_class вернёт A. Если B наследуется от A через произвольную глубокую иерархию, B.base_class вернёт A.
Если B < A и C < B, и если A является #abstract_class, то B.base_class и C.base_class вернут B, поскольку A является абстрактным классом.
# File activerecord/lib/active_record/inheritance.rb, line 69
def base_class
unless self < Base
raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
end
if superclass == Base || superclass.abstract_class?
self
else
superclass.base_class
end
end Возвращает true, если этому классу не требуется условие типа STI. Возвращает false, если условие типа STI необходимо применять.
# File activerecord/lib/active_record/inheritance.rb, line 36
def descends_from_active_record?
if self == Base
false
elsif superclass.abstract_class?
superclass.descends_from_active_record?
else
superclass == Base || !columns_hash.include?(inheritance_column)
end
end Определяет, является ли один из переданных атрибутов столбцом наследования, и если столбец наследования доступен для атрибутов, инициализирует экземпляр заданного подкласса вместо базового класса.
# File activerecord/lib/active_record/inheritance.rb, line 17
def new(*args, &block)
if abstract_class? || self == Base
raise NotImplementedError, "#{self} is an abstract class and cannot be instantiated."
end
attrs = args.first
if subclass_from_attributes?(attrs)
subclass = subclass_from_attributes(attrs)
end
if subclass
subclass.new(*args, &block)
else
super
end
end # File activerecord/lib/active_record/inheritance.rb, line 103 def sti_name store_full_sti_class ? name : name.demodulize end
# File activerecord/lib/active_record/inheritance.rb, line 51
def symbolized_base_class
ActiveSupport::Deprecation.warn("ActiveRecord::Base.symbolized_base_class is deprecated and will be removed without replacement.")
@symbolized_base_class ||= base_class.to_s.to_sym
end # File activerecord/lib/active_record/inheritance.rb, line 56
def symbolized_sti_name
ActiveSupport::Deprecation.warn("ActiveRecord::Base.symbolized_sti_name is deprecated and will be removed without replacement.")
@symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class
end Защищённые методы экземпляров
Возвращает тип класса записи, используя текущий модуль в качестве префикса. Так, потомки MyApp::Business::Account будут отображаться как MyApp::Business::AccountSubclass.
# File activerecord/lib/active_record/inheritance.rb, line 111
def compute_type(type_name)
if type_name.match(/^::/)
# If the type is prefixed with a scope operator then we assume that
# the type_name is an absolute reference.
ActiveSupport::Dependencies.constantize(type_name)
else
# Build a list of candidates to search for
candidates = []
name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" }
candidates << type_name
candidates.each do |candidate|
begin
constant = ActiveSupport::Dependencies.constantize(candidate)
return constant if candidate == constant.to_s
# We don't want to swallow NoMethodError < NameError errors
rescue NoMethodError
raise
rescue NameError
end
end
raise NameError.new("uninitialized constant #{candidates.first}", candidates.first)
end
end
© 2004–2016 David Heinemeier Hansson
Licensed under the MIT License.