I'd like to build a function "create" that gives me the following capabilities :
zoo=[]
zoo << create(:dog,4)
zoo[0].class #Dog class
myDog=zoo[0].new("foobar") #instance of Dog
myDog.legs #4 legs because my dog is a Dog
zoo[0].class.legs #4
zoo[0].class.superclass #Animal
zoo[0].class.superclass.legs #whatever, but they have legs
"create(:dog,4)" produces a new class Dog that inherits Animal etc
Can you help about this apparently simple metaprogramming question ?
class Animal
def self.legs=(legs)
@legs = legs
end
def self.legs
@legs
end
def legs
self.class.legs
end
end
def create(sym, legs)
klass = Object.const_set(sym.to_s.capitalize, Class.new(Animal))
klass.legs = legs
klass
end
kdog = create(:dog, 4)
kalien = create(:alien, 3)
dog = kdog.new
alien = kalien.new
puts kdog
puts kdog.class
puts kdog.superclass
puts kdog.legs
puts dog.class
puts dog.legs
puts "------"
puts kalien
puts kalien.class
puts kalien.superclass
puts kalien.legs
puts alien.class
puts alien.legs
Output:
Dog
Class
Animal
4
Dog
4
------
Alien
Class
Animal
3
Alien
3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With