Sha256: d379f2948286a397d8332ecdfbca1363fe617ea0af363f0cb6ac4269fbe9bda3

Contents?: true

Size: 1.5 KB

Versions: 33

Compression:

Stored size: 1.5 KB

Contents

module Redcar
  class Resource
    attr_reader :block, :task
    
    def self.task_queue
      Redcar.app.task_queue
    end
    
    def initialize(description=nil, &block)
      @description = description
      @block  = block
      @value  = nil
      @future = nil
      @task   = nil
      @mutex  = Mutex.new
    end
    
    def value
      return @value if @value
      
      object = nil
      @mutex.synchronize do
        if @future
          if @task.pending?
            @task.cancel
            @future = nil
            @task   = nil
            object = @block
          else
            object = @future
          end
        else
          object = @block
        end
      end
      
      case object
      when Proc
        @value = object.call
      else
        @value = object.get
      end
    end
    
    def compute
      @mutex.synchronize do
        unless @task and @task.pending?
          @task = Resource::Task.new(self)
          @task.description = @description
          @future = Resource.task_queue.submit(@task)
        end
      end
    end
    
    class Task < Redcar::Task
      def initialize(resource)
        @resource = resource
      end
      
      def execute
        result = @resource.block.call
        @resource.send(:set_value_from_background, result)
        result
      end
    end
    
    private
    
    def set_value_from_background(value)
      @mutex.synchronize do
        @value  = value
        @future = nil
        @task   = nil
      end
    end
  end
end

Version data entries

33 entries across 33 versions & 1 rubygems

Version Path
redcar-0.10 plugins/core/lib/core/resource.rb
redcar-0.9.2 plugins/core/lib/core/resource.rb
redcar-0.9.1 plugins/core/lib/core/resource.rb
redcar-0.9.0 plugins/core/lib/core/resource.rb
redcar-0.8.1 plugins/core/lib/core/resource.rb
redcar-0.8 plugins/core/lib/core/resource.rb
redcar-0.7 plugins/core/lib/core/resource.rb
redcar-0.6.1 plugins/core/lib/core/resource.rb
redcar-0.6 plugins/core/lib/core/resource.rb
redcar-0.6.1dev plugins/core/lib/core/resource.rb
redcar-0.5.1 plugins/core/lib/core/resource.rb
redcar-0.5 plugins/core/lib/core/resource.rb
redcar-0.5.6dev plugins/core/lib/core/resource.rb
redcar-0.5.5dev plugins/core/lib/core/resource.rb
redcar-0.5.4dev plugins/core/lib/core/resource.rb
redcar-0.5.3dev plugins/core/lib/core/resource.rb
redcar-0.5.2dev plugins/core/lib/core/resource.rb
redcar-0.5.1dev plugins/core/lib/core/resource.rb
redcar-0.4.1 plugins/core/lib/core/resource.rb
redcar-0.4 plugins/core/lib/core/resource.rb