Search code examples
rubyclassvariablesinheritance

ruby / ability to share a single variable between multiple classes


For general classes manipulation understanding; given the following use case :

class Child1
  def process var
    'child1' + var
  end
end

class Child2
  def process var
    'child1' + var
  end
end

class Child3
  def process var
    'child3' + var
  end
end

...

class Master
  attr_reader :var
  def initialize(var)
    @var = var
  end

  def process
    [
      Child1.new.process(var),
      Child2.new.process(var),
      Child3.new.process(var)
    ]
  end
end

by some kind of inheritance or structure, would there be a way to have var available to all children ?

Meaning :

class Child1 < Inherited
  def process
    'child1' + var
  end
end

...

class Master
  ...
  def process
    [
      Child1.new.process,
      ...
    ]
  end
end

I don't know my thing enough to find the preferred approached (eventhough the first example above do work ok, while not being the most elegant probably); thanks for any guidance


Solution

  • 4 years later, ended up relying almost systematically to inheritance for such things, using simple def's, super sometimes, etc... all those are ruby classes native behaviours.

    class Base
      private
    
      def class_variable
        0
      end
    end
    
    class B < Base
      def update
        # class_variable is made available by the Base inheritance
        class_variable + 1
      end
    end
    
    class C < B
      def update_from_base
        # class_variable is made available by A
        # B inherit from Base, so we do have class_variable available here
        # -> will output 2
        class_variable + 2
      end
    
     def update
        # as we inherit from B, and as B provides and update method
        # using super, we're then extending the def update available from B
        # -> will output 3 
        super + 2
      end
    end
    

    ... and so on. It is a simple example; but scales well even for complex business logic, as it tends to help you focus on shared parts of your code base while you organize your classes hierarchically in terms of responsibilities.