1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Extract class-finder method from instantiate

This commit is contained in:
Jeremy Kemper 2009-09-17 17:26:29 -07:00
parent 7701c6f1c0
commit 3fc2d1ebd9

View file

@ -1648,34 +1648,10 @@ module ActiveRecord #:nodoc:
# single-table inheritance model that makes it possible to create # single-table inheritance model that makes it possible to create
# objects of different types from the same table. # objects of different types from the same table.
def instantiate(record) def instantiate(record)
object = object = find_sti_class(record[inheritance_column]).allocate
if subclass_name = record[inheritance_column]
# No type given.
if subclass_name.empty?
allocate
# Ignore type if no column is present since it was probably object.instance_variable_set(:'@attributes', record)
# pulled in from a sloppy join. object.instance_variable_set(:'@attributes_cache', {})
elsif !columns_hash.include?(inheritance_column)
allocate
else
begin
compute_type(subclass_name).allocate
rescue NameError
raise SubclassNotFound,
"The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " +
"This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
"Please rename this column if you didn't intend it to be used for storing the inheritance class " +
"or overwrite #{self.to_s}.inheritance_column to use another column for that information."
end
end
else
allocate
end
object.instance_variable_set("@attributes", record)
object.instance_variable_set("@attributes_cache", Hash.new)
object.send(:_run_find_callbacks) object.send(:_run_find_callbacks)
object.send(:_run_initialize_callbacks) object.send(:_run_initialize_callbacks)
@ -1683,6 +1659,22 @@ module ActiveRecord #:nodoc:
object object
end end
def find_sti_class(type_name)
if type_name.blank? || !columns_hash.include?(inheritance_column)
self
else
begin
compute_type(type_name)
rescue NameError
raise SubclassNotFound,
"The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " +
"This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
"Please rename this column if you didn't intend it to be used for storing the inheritance class " +
"or overwrite #{name}.inheritance_column to use another column for that information."
end
end
end
# Nest the type name in the same module as this class. # Nest the type name in the same module as this class.
# Bar is "MyApp::Business::Bar" relative to MyApp::Business::Foo # Bar is "MyApp::Business::Bar" relative to MyApp::Business::Foo
def type_name_with_module(type_name) def type_name_with_module(type_name)