1

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?

farith
  • 23
  • 6
  • What do you mean by _instance_ in your question? I.e. at what time should the decision be taken, which class is going to be included? – user1934428 Jul 30 '20 at 07:42
  • 1
    Why do you specifically want an answer for a no-longer-supported version of Ruby on Rails? What makes you think this answer is specific to Rails and moreover to a specific version of Rails that is over 7 years old? – Jörg W Mittag Jul 30 '20 at 07:45

1 Answers1

2

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.

max pleaner
  • 26,189
  • 9
  • 66
  • 118