brew/Library/Homebrew/lazy_object.rb

29 lines
662 B
Ruby
Raw Normal View History

2020-10-10 14:16:11 +02:00
# typed: true
# frozen_string_literal: true
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)
__getobj__.is_a?(klass) || super
end
2018-07-30 19:29:18 +02:00
end