ruby - A method of telling if object supports a method -
i trying write file handling code opens file, obtains data file, closes file.
my first encountered problem if use the
file.open(...) |fd| var = fd.size end
method of opening file ensures closed @ end, variables inside limited scope of block.
one way solve predefine variables outside of block, doesn't seem right...
my other solution use ensure
block close handles so:
def test(file) return if file == nil || file == "" fd = file.open(file, ...) var = fd.size ensure fd.close end
but doing if file handle not exist or not created, perhaps logic before handling errors, ensure
block throws nil:nilclass exception.
is there clean way handle files allows me pull different stats (including reading of contents) in way can guarantee file closes, , don't have predefine variables escape scope of block? (bonus points if works socket handles well)
thanks!
you can put conditional on method call fail if fd nil.
ensure fd.close if fd end
you can use :respond_to? if want check if method supported
ensure fd.close if fd.respond_to? :close end
if want fancy, rails has helper method (that can borrow) trying send method object. http://apidock.com/rails/object/try
you able change code to
ensure fd.try(:close) end
Comments
Post a Comment