Include different module into same class based on use case

70 views Asked by At

If there are 2 modules - module Abc and module Bcd and one class - class Efg.

Now we want to include module Abc into class Efg in once instance and need to include module Bcd into class Efg in another instance but not both modules at same time.

Is it possible to do in Ruby classes?

1

There are 1 answers

0
max pleaner On BEST ANSWER

If I am understanding your question properly then I think you can use singleton_class to include a module only for a specific instance of a class:

inst1 = Efg.new
inst2 = Efg.new
inst3 = Efg.new

inst1.singleton_class.include Asd
inst2.singleton_class.include Bcd

Now inst1 will have the methods from Asd and inst2 will have the methods from Bcd. inst3 will have none of the methods.