brew/Library/Homebrew/lazy_object.rb

33 lines
796 B
Ruby
Raw Normal View History

2020-10-10 14:16:11 +02:00
# typed: true
# frozen_string_literal: true
2023-10-08 09:36:08 -07:00
require "delegate"
2020-08-09 03:14:44 +02:00
# An object which lazily evaluates its inner block only once a method is called on it.
#
# @api private
2018-07-30 19:29:18 +02:00
class LazyObject < Delegator
def initialize(&callable)
super(callable)
end
def __getobj__
# rubocop:disable Naming/MemoizedInstanceVariableName
2018-07-30 19:29:18 +02:00
return @__delegate__ if defined?(@__delegate__)
2018-09-17 02:45:00 +02:00
2018-07-30 19:29:18 +02:00
@__delegate__ = @__callable__.call
# rubocop:enable Naming/MemoizedInstanceVariableName
2018-07-30 19:29:18 +02:00
end
def __setobj__(callable)
@__callable__ = callable
end
2021-01-13 09:22:06 +01:00
# Forward to the inner object to make lazy objects type-checkable.
def is_a?(klass)
2023-11-05 08:55:58 -08:00
# see https://sorbet.org/docs/faq#how-can-i-fix-type-errors-that-arise-from-super
T.bind(self, T.untyped)
2021-01-13 09:22:06 +01:00
__getobj__.is_a?(klass) || super
end
2018-07-30 19:29:18 +02:00
end