3

I have a set of objects that themselves each create a bunch of helper objects. Inside of the helper objects I need access to many of the parents instance variables, such as "name", a logger object and some more.

I could initialize the helper objects with all of the needed variables but that seems quite tedious. Is there a way to make the parents instance variables known to all the objects owned by it?

I have found a wealth of similar questions but most are about class variables and inheritance so I was not able to find a solution yet.

Example & rubyfiddle:

class Helper def initialize() end def complexStuff puts # Parent object name end end class Main attr_accessor :name def initialize( name ) @name = name @helper = Helper.new end def update puts "[(#{name}).update]" @helper.complexStuff end end instance1 = Main.new( "Instance 1" ) instance2 = Main.new( "Instance 2" ) instance1.update instance2.update 

rubyfiddle

0

1 Answer 1

2

Why not just pass the parent in?

class Helper def initialize(parent) @parent = parent end def complexStuff puts @parent.name # Parent object name end end class Main attr_accessor :name def initialize( name ) @name = name @helper = Helper.new(self) end def update puts "[(#{name}).update]" @helper.complexStuff end end instance1 = Main.new( "Instance 1" ) instance2 = Main.new( "Instance 2" ) instance1.update instance2.update 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.