File: promise.rb

package info (click to toggle)
rails 2%3A7.2.2.1%2Bdfsg-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 43,352 kB
  • sloc: ruby: 349,799; javascript: 30,703; yacc: 46; sql: 43; sh: 29; makefile: 27
file content (84 lines) | stat: -rw-r--r-- 1,876 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# frozen_string_literal: true

module ActiveRecord
  class Promise < BasicObject
    undef_method :==, :!, :!=

    def initialize(future_result, block) # :nodoc:
      @future_result = future_result
      @block = block
    end

    # Returns whether the associated query is still being executed or not.
    def pending?
      @future_result.pending?
    end

    # Returns the query result.
    # If the query wasn't completed yet, accessing +#value+ will block until the query completes.
    # If the query failed, +#value+ will raise the corresponding error.
    def value
      return @value if defined? @value

      result = @future_result.result
      @value = if @block
        @block.call(result)
      else
        result
      end
    end

    # Returns a new +ActiveRecord::Promise+ that will apply the passed block
    # when the value is accessed:
    #
    #   Post.async_pick(:title).then { |title| title.upcase }.value
    #   # => "POST TITLE"
    def then(&block)
      Promise.new(@future_result, @block ? @block >> block : block)
    end

    [:class, :respond_to?, :is_a?].each do |method|
      define_method(method, ::Object.instance_method(method))
    end

    def inspect # :nodoc:
      "#<ActiveRecord::Promise status=#{status}>"
    end

    def pretty_print(q) # :nodoc:
      q.text(inspect)
    end

    private
      def status
        if @future_result.pending?
          :pending
        elsif @future_result.canceled?
          :canceled
        else
          :complete
        end
      end

      class Complete < self # :nodoc:
        attr_reader :value

        def initialize(value)
          @value = value
        end

        def then
          Complete.new(yield @value)
        end

        def pending?
          false
        end

        private
          def status
            :complete
          end
      end
  end
end