Skip to content

Instantly share code, notes, and snippets.

@bomberstudios
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bomberstudios/ac3d192e51c2cd1b10cb to your computer and use it in GitHub Desktop.
Save bomberstudios/ac3d192e51c2cd1b10cb to your computer and use it in GitHub Desktop.
# Please note: this is an oversimplification of the real problem :)
# Say you have this class definition:
class One
attr_accessor :children
def initialize data
puts "Initialize One"
@children = data.map do |item|
item = Two.new(item)
end
end
end
class Two
attr_accessor :children
def initialize data
puts "Initialize Two"
@children = data.map { |item| item = Three.new(item) }
end
end
class Three
attr_accessor :data
def initialize data
puts "Initialize Three"
@data = data
end
end
# Now I create a new instance of the One class:
data = [["foo", "bar"], ["foo", "bar"]]
myOne = One.new(data)
# I can now do this:
puts myOne.children.first.children.first.data # "foo"
# Now my question is: how would I access class One methods from class Three?
# i.e: imagine I need to access the @children property of class One from a
# method in class Three. What would be a good way to do that, other than passing
# a 'parent' parameter to every class constructor in the chain?
#
# Thanks in advance!
#
@cavalle
Copy link

cavalle commented Sep 19, 2014

It's hard to tell with an abstract example (i.e. without understanding why do you need to call One from Three), but if the relation between the classes is naturally hierarchical (e.g. Series -> Seasons -> Episodes), passing a reference back to the parent object might be a fine solution.

@bomberstudios
Copy link
Author

I have Document -> Pages -> Layers, so I guess that counts as "naturally hierarchical". I actually started doing the "pass a reference back to the parent" part, but then I thought that maybe Ruby already had something like object.parent and didn't feel like reinventing the wheel.

Thanks a lot : )

@jelledelaender
Copy link

"passing a reference back to the parent object might be a fine solution."

Yes, but this can also be fixed by following the design patterns more closely.

Seems 2 and 3 are models (containing data), where he want to add some logic to 3 that's doing more than related to his model, that should be moved to a controller class.

A controller class should known the structs of the models and be able to make all links, anyway, as quick solution, passing a reference is a fine solution indeed.

In which case does a Layer need to know on what Page he is on?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment