Reputation: 1000
Consider this code:
class Bar
def initialize
puts 'Hi from class Bar.'
exit
end
end
class Foo
def initialize
loop {
case $stdin.gets.chomp
when 'foo'
puts 'Hi from class Foo.'
when 'bar'
Bar.new
end
}
end
end
Can I ignore the exit in class Bar somehow?
It terminates my loop. I don't want that.
Note - the real code base is much larger and more complicated than that. But it boils down to this question whether I can ignore exit() or not.
Upvotes: 1
Views: 389
Reputation: 87271
loop {
begin
Bar.new
rescue SystemExit
p $! #: #<SystemExit: exit>
end
}
This will print #<SystemExit: exit>
in an infinite loop, without ever exiting.
Upvotes: 6
Reputation: 61875
One hackish way to define an exit
method in context:
class Bar; def exit; end; end
This works because exit
in the initializer will be resolved as self.exit
1. In addition, this approach allows using the object after it has been created, as in: b = B.new
.
But really, one shouldn't be doing this: don't have exit
(or even puts
) there to begin with.
(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)
1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit
normally resolves to Object#exit
. However, this can be changed by introducing an overridden method as shown - nothing fancy.
Upvotes: 2