Reputation: 181
How we can overwrite the class name of an object ?
Example:
$ irb
irb(main):001:0> class Man
irb(main):002:1> end
=> nil
irb(main):003:0> obj = Man.new
=> #<Man:0xb7756464>
irb(main):004:0> puts obj.class
Man
=> nil
I want some thing like that
puts obj.class
Van instead of Man
=> nil
Upvotes: 1
Views: 259
Reputation: 81520
I know how to overwrite the apparent class name:
class Man
def self.inspect
"Van"
end
end
irb(main):007:0* m = Man.new
=> #<Man:0x144ace0>
irb(main):008:0> m.class
=> Van
(ActiveRecord does something similar)
But doing a convincing forgery of object inspection is tricky. I don't know how to do the 0xb7756464
bit in #<Man:0xb7756464>
, so I don't know how to re-implement Man#inspect
.
Upvotes: 0
Reputation: 62387
Remeber, that class
method does not return a class name (a string), but actually a constant class object. You'd need to create a class Van
first, then override obj.class
method, so that it returns Van
instead of Man
irb(main):001:0> class Man
irb(main):002:1> end
=> nil
irb(main):003:0> class Van
irb(main):004:1> end
=> nil
irb(main):005:0> obj = Man.new
=> #<Man:0x25043b8>
irb(main):006:0> def obj.class
irb(main):007:1> Van
irb(main):008:1> end
=> nil
irb(main):009:0> obj.class
=> Van
is_a?
and other methods might need overriding too
irb(main):010:0> obj.is_a? Man
=> true
irb(main):011:0> obj.is_a? Van
=> false
Upvotes: 0