我试图将继承与经典"类型"属性。在初始化用户类型:" Admin"我希望有一个管理对象,但它会返回用户对象。我怎样才能使一个类像一个模型一样行动,并使它像STI一样行动?
class User
include ActiveModel::Model
attr_accessor :type
def persisted?
false
end
end
class Admin < User
end
user = User.new(type: "Admin")
#=> #<User:0x007ff68a1ade60 @type="Admin">
答案 0 :(得分:1)
class User
include ActiveModel::Model
def self.build(type: 'User')
klass = Kernel.const_get(type)
if klass.ancestors.include?(User)
klass.new
else
raise "you are just not my type"
end
end
def persisted?
false
end
end
class Admin < User
end
> u = User.build(type: 'Admin) # => instance of Admin
> u = User.build # => instance of User
> u = User.build(type: 'Object') # => RuntimeError