Get slot from containing object in nested object

118 Views Asked by At

I have a set of nested objects, and need to get a slot from the containing object. Can it be done?

Example:

Foo := Object clone do(
    a := "hello"

    Bar := Object clone do(
        b := Foo a  # How to get `Foo a` here?
    )
)

From the above code, I get an exception in the nested object Bar when accessing Foo:

Exception: Object does not respond to 'Foo'

The reason I would like to have these as nested objects, is because it would make it easier (IMO) to make the application more modular. If it was possible I could easily do something like

Foo := Object clone do(
    someSlot := "Some value"

    Bar := doRelativeFile("./folder/bar.io")
)

and in folder/bar.io use Foo someSlot if needed.

Think of e.g. someSlot as a database connection, and Bar as a data-model needing that database connection.

1

There are 1 best solutions below

1
On BEST ANSWER

I solved by creating an intialize method in the nested object, which takes the containing object as a parameter and returns self (i.e. the nested object.

So I can have two files like this:

  1. a.io

    Foo := Object clone do(
        foo := "foobar"
    
        Bar := doRelativeFile("./b.io") initialize(thisContext)
    )
    
  2. b.io

    Bar := Object clone do(
        initialize := method(parent,
            writeln("parent foo is ", parent foo)
            return self
        )
    )
    

While not a perfect solution, it should work well enough for my purposes.