Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create class dynamically, with inheritance and particular accessors

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 ?

like image 778
JCLL Avatar asked Jul 22 '11 19:07

JCLL


1 Answers

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
like image 50
Casper Avatar answered Sep 28 '22 03:09

Casper