BigW Consortium Gitlab

lazy.rb 749 Bytes
Newer Older
Yorick Peterse committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
module Gitlab
  # A class that can be wrapped around an expensive method call so it's only
  # executed when actually needed.
  #
  # Usage:
  #
  #     object = Gitlab::Lazy.new { some_expensive_work_here }
  #
  #     object['foo']
  #     object.bar
  class Lazy < BasicObject
    def initialize(&block)
      @block = block
    end

    def method_missing(name, *args, &block)
      __evaluate__

19
      @result.__send__(name, *args, &block) # rubocop:disable GitlabSecurity/PublicSend
Yorick Peterse committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
    end

    def respond_to_missing?(name, include_private = false)
      __evaluate__

      @result.respond_to?(name, include_private) || super
    end

    private

    def __evaluate__
      @result = @block.call unless defined?(@result)
    end
  end
end