1

I have two base class and multiple child class.. Based on the type, the child class dynamically inherit from the base parent class.

Eg:

 class Dad
     def initialize
         #initialize some stuffs
     end
 end

 class Mom 
     def initialize
         #initialize some stuffs
     end     
 end

 class child
 def initialize
        super
        #initialize some stuffs
     end
 end

 class child2
     def initialize
       super
       #initialize some stuffs
     end     
 end

 class child3
 end

How to assign parent class to child class dynamically? At the time of creation only, I will choose child class and its appropriate parent class to proceed further

ErRoR
  • 503
  • 5
  • 12
  • Why do you want to do that? What do you try to achieve? – spickermann May 29 '15 at 09:57
  • 1
    To give in deep explanation, Lets assume there are two types of company, service & product ( parent class) . Along with that there are 'n' types of sub company which inherit parent class features and also it will have it's own features and functionality. At the time of creation only, I will choose child class and its appropriate parent class to proceed further.. – ErRoR May 29 '15 at 10:12

2 Answers2

1

Normally you can't, but you can with some 'evil'.

First of all you need to install a gem called 'RubyInline' for this to work.

Then you monkey patch the Class class like so:

require 'inline'
class Class
    inline do |builder|

        builder.c %{            
            VALUE set_super(VALUE sup) {
                RCLASS(self)->super = sup;
                return sup;
            }
        }

        builder.c %{
            VALUE get_super() {
                return RCLASS(self)->super;
            }
        }

    end
end

This will allow you to get and set the super class (directly inherited class) for a particular class.

Then you can just do:

Child2.set_super(New_Parent_Class)
Thermatix
  • 2,757
  • 21
  • 51
0

Perhaps you are looking for this

Child = Class.new Parent do
  def foo
    "foo"
  end
end

Child.ancestors   # => [Child, Parent, Object, Kernel]
Child.new.bar     # => "bar"
Child.new.foo     # => "foo"

Where parent is Mum/Dad

Dan
  • 516
  • 5
  • 14