I want to avoid reevaluation of a value in method call. Untill now, I was doing this:
def some_method
@some_method ||= begin
# lot\'s of code
end
end
I use the memoist gem, which lets you easily memoize a method without having to alter your original method or create two methods.
So for example, instead of having two methods, file_size
and calculate_file_size
, and having to implement the memoization yourself with an instance variable:
def file_size
@file_size ||= calculate_file_size
end
def calculate_file_size
# code to calculate the file size
end
you can just do this:
def file_size
# code to calculate the file size
end
memoize :file_size
Each memoized function comes with a way to flush the existing value.
object.file_size # returns the memoized value
object.file_size(true) # bypasses the memoized value and rememoizes it
So calling object.file_size(true)
would be the equivalent of calling object.calculate_file_size
...