Search code examples
ruby-on-railsruby

is there way to convert object into another class in ruby


let say I have model

User < ActiveRecord::Base
end

and his STI brother

MasqueradeUser < User
end 

masquerade_user =  MasqueradeUser.find 123
masquerade_user.class
# => MasqueradeUser

Ridiculous as it sounds, is possible to convert this object back to parent class User

masquerade_user.some_magic.class   # => User

I know I can override methods like mode_name, is_a?(User) and other so that MasqueradeUser will return values like User

MasqueradeUser < User
  def model_name
    'User'
  end
end 

I was just wondering if there is a way to completely downgrade object to parent class instance


Solution

  • You can use becomes function of ActiveRecord - see here.