Ruby with spreadsheet getting stuck on exceptions
I have the following code:
require 'spreadsheet'
class MyObject
def initialize
@workbook = Spreadsheet::open('foo.xls', 'r')
end
end
h = MyObject.new
h.inexistent
Running it, Ruby (1.9.开发者_如何学JAVA2p290 [i386-mingw32]) will print "test.rb:10:in '<main>'
", and then start continuously eating up RAM until it gets killed.
Obviously, this is the beginning of the exception message "test.rb:10:in '<main>': undefined method 'inexistent' for #<MyObject:0xfb5140> (NoMethodError)
".
Without an exception being thrown, the program will terminate normally.
What could be causing this strange behaviour?
Note that inexistent
does not exist. This is intentional in order to demonstrate the behaviour when an exception is thrown.
This is just a shot in the dark:
I believe the answer to your problem is that when the exception is thrown the spreadsheet object is being converted into its string representation, and this makes even a small spreadsheet take up a large amount of memory temporarily.
I couldn't reproduce your ever growing memory, but in my case even with a 22k spreadsheet I was able to make irb consume about 140 megs of ram before it stabilized back by inspecting the spreadsheet object.
A simple way to test this is to add a custom to_s method for your MyObject which avoids the spreadsheet dump.
class MyObject
def initialize
@workbook = Spreadsheet::open('foo.xls', 'r')
end
def to_s
"Put something more useful here"
end
end
精彩评论