Skip to content

Instantly share code, notes, and snippets.

@baroquebobcat
Created May 14, 2012 22:49
Show Gist options
  • Select an option

  • Save baroquebobcat/2697939 to your computer and use it in GitHub Desktop.

Select an option

Save baroquebobcat/2697939 to your computer and use it in GitHub Desktop.
Mirah: some thoughts on this & self in closures
# Some of my thoughts
#
# this one's easy
addListener do |event|
self # < outer scope self
end
# but what about
addListener do
def respond event
self # < closure self? or outer self
end
end
# if self is a closure's self, what about
@foo = 1
addListener do
def respond event
@foo.wob event # whose @foo are you?
end
end
# even more ambiguous
@foo = 1
addListener do
def initarable
@foo = :wargh
end
def respond event
@foo.wob event # whose @foo are you? really!
end
end
# could add a special self only for closures
addListener do
def respond event
self # < outer self
sekret_self # < closure self
end
end
# but that doesn't solve instance variables
#
# Do people care about instance variables and self on their closures?
#
# The simplest fix is to have all scoping defer to the outer scope.
# But then you can't do this
addListener do
def genericRespond event
puts "flibble-flabble"
end
def respondA event
genericRespond event
end
def respondB event
genericRespond event
end
end
# I guess you could work around that by having that method on the
# outer scope
def genericRespond event
puts "flibble-flabble"
end
addListener do
def respondA event
genericRespond event
end
def respondB event
genericRespond event
end
end
# And what happens when you've got nested closures?
addListener do
def respond event
event.backToTheFuture do
puts "Doc!"
self.run # who is self now?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment