Skip to content

Instantly share code, notes, and snippets.

@localhostdotdev
Last active March 30, 2019 11:57
Show Gist options
  • Save localhostdotdev/474a0f91293715647b8a1d5652314790 to your computer and use it in GitHub Desktop.
Save localhostdotdev/474a0f91293715647b8a1d5652314790 to your computer and use it in GitHub Desktop.
e.g. `object = Lazy.new(function: -> (id) { somethingThatFetch(id) }, value: 123)`. then `variable.anything` will load up the object
class Lazy
attr_reader :value
def initialize(function:, value:)
@function = function
@value = value
@cached = nil
@is_cached = false
end
def hash
value.hash
end
def eql?(other)
if other.is_a?(Lazy)
value == other.value
else
value == other
end
end
def <=>(other)
if other.is_a?(Lazy)
value <=> other.value
else
value <=> other
end
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
cached.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