File: memoizable.rb

package info (click to toggle)
ruby-dry-container 0.7.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 236 kB
  • sloc: ruby: 976; makefile: 4
file content (49 lines) | stat: -rw-r--r-- 1,125 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require 'dry/container/item'

module Dry
  class Container
    class Item
      # Memoizable class to store and execute item calls
      #
      # @api public
      #
      class Memoizable < Item
        # @return [Mutex] the stored mutex
        attr_reader :memoize_mutex

        # Returns a new Memoizable instance
        #
        # @param [Mixed] item
        # @param [Hash] options
        #
        # @raise [Dry::Container::Error]
        #
        # @return [Dry::Container::Item::Base]
        def initialize(item, options = {})
          super
          raise_not_supported_error unless callable?

          @memoize_mutex = ::Mutex.new
        end

        # Returns the result of item call using a syncronized mutex
        #
        # @return [Dry::Container::Item::Base]
        def call
          memoize_mutex.synchronize do
            @memoized_item ||= item.call
          end
        end

        private

        # @private
        def raise_not_supported_error
          raise ::Dry::Container::Error, 'Memoize only supported for a block or a proc'.freeze
        end
      end
    end
  end
end