Reputation: 5760
The File class has a class method called size which takes a path and returns the size of the file that the path points to. What would be a reason to not have a instance method called size on a File.
Here is why it matters to me.
I am using the httpclient gem. I use this to upload a file to a server. For example I would use the following statement to upload a file to the server using httpclient
file=File.open("foo.txt")
HttpClient.new.put("/upload", file)
If I do not add the size instance method to the File class it complains so I went ahead and monkey patched it as follows,
class File
def size
@file_size ||= File.size(self.path)
end
end
This works but I wonder if there is a reason why the size method was not added as an instance method and if there is a better way to do what I have done.
Upvotes: 3
Views: 165
Reputation: 211670
This method is present in 1.9.2 as documented so you may want to avoid adding this patch if the method is already defined.
Another thing you've done is cached the result, which is probably bad form as that can change as the file is appended to, truncated, or unlinked.
Upvotes: 8