Skip to content

Instantly share code, notes, and snippets.

@localhostdotdev
Last active April 23, 2019 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save localhostdotdev/643887d5a169886f238aa2345fcc2f5e to your computer and use it in GitHub Desktop.
Save localhostdotdev/643887d5a169886f238aa2345fcc2f5e to your computer and use it in GitHub Desktop.
Lazy: fetch deep values only when you need to
# 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