Reputation: 6165
Suppose I have a setup like this:
class Foo
attr_accessor :bar
def initialize
@bar = Bar.new
end
end
class Bar
def bar_method
self.class # => Bar
whatever???.class # => Foo
end
end
foo = Foo.new
foo.bar.bar_method
I know that I can set up the method like this:
def bar_method(selfs_self)
selfs_self.class # => Foo
end
And call the method like this: foo.bar.bar_method(foo)
to get what I want. But that seems pretty redundant. Is there any way, inside of bar_method
, that I can get a reference to foo
, without specifically passing in a reference to it?
Upvotes: 2
Views: 268
Reputation: 6041
No.
Usually this is done by passing a reference to the parent object when initializing child objects, like:
class Foo
attr_accessor :bar
def initialize
@bar = Bar.new(self)
end
end
class Bar
attr_reader :foo
def initialize(foo)
@foo = foo
end
def bar_method
self.class # => Bar
foo.class # => Foo
end
end
Upvotes: 3