Created
April 1, 2014 03:17
-
-
Save mattconnolly/9907062 to your computer and use it in GitHub Desktop.
A let method to memoize values that could be nil.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Let | |
def let(name, &block) | |
ivar = "@#{name}".to_sym | |
if instance_variable_defined?(ivar) | |
instance_variable_get(ivar) | |
else | |
instance_variable_set(ivar, instance_eval(&block)) | |
end | |
end | |
end | |
class Thing | |
include Let | |
def result | |
let(:result) { some_expensive_calculation_that_could_return_nil } | |
end | |
end | |
t = Thing.new | |
t.result #=> calculated result that could be nil | |
t.result #=> cached result that could be nil | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment