Last active
April 23, 2019 13:53
-
-
Save localhostdotdev/643887d5a169886f238aa2345fcc2f5e to your computer and use it in GitHub Desktop.
Lazy: fetch deep values only when you need to
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
# Example: Lazy.new(lambda { |id| API::HackerNews.item(id) }, 0) | |
class Lazy | |
attr_reader :value | |
def initialize(function:, value:) | |
@function = function | |
@value = value | |
@cached = nil | |
@is_cached = false | |
end | |
def method_missing(method, *args, &block) | |
cached.send(method, *args, &block) | |
end | |
def cached | |
unless @cached | |
@cached = @function.call(value) | |
@is_cached = true | |
end | |
@cached | |
end | |
def cached? | |
@is_cached | |
end | |
def to_s | |
value.to_s | |
end | |
def inspect | |
"#<Lazy @value=#{value.inspect} cached?=#{cached?.inspect}>" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment