Skip to content

Instantly share code, notes, and snippets.

@adam12
Forked from localhostdotdev/lazy.rb
Created April 23, 2019 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adam12/ce411e293e12ea43979518724c22afa4 to your computer and use it in GitHub Desktop.
Save adam12/ce411e293e12ea43979518724c22afa4 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