Sha256: ebb3c98921fd06e91178d76766eb2ca30acedfb118318a5919e74a12db2c02cd

Contents?: true

Size: 1.6 KB

Versions: 1

Compression:

Stored size: 1.6 KB

Contents

# encoding: utf-8

module Hatetepe
  class Promise < ::Promise
    include ::Promise::Progress

    def fulfill(value = nil)
      super(value)
    end

    def reject(reason = nil)
      super(reason)
    end

    def sync
      if fulfilled?
        return value
      elsif rejected?
        return reason
      end

      sync!
    end

    def sync!
      fiber = Fiber.current
      resume = proc do |arg|
        EM.next_tick { fiber.resume(arg) }
        # fiber.resume(arg)
      end

      self.then(resume, resume)
      Fiber.yield
    end

    private

    def defer(callback, arg)
      EM.next_tick { safe_dispatch(callback, arg) }
      # safe_dispatch(callback, arg)
    end

    def safe_dispatch(callback, arg)
      callback.dispatch(arg)
    # rescue => error
    #   ...
    end

    module Attribute
      def self.included(klass)
        klass.extend(ClassMethods)
      end

      def initialize(*args)
        super(*args)
        promises.map { |name| send(name) }
      end

      private

      def promises
        self.class.send(:promises)
      end

      def get_or_set_promise(ivar)
        if instance_variable_defined?(ivar)
          instance_variable_get(ivar)
        else
          instance_variable_set(ivar, Promise.new)
        end
      end

      module ClassMethods
        private

        def promises
          @promises ||= []
        end

        def promise(name)
          promises << name
          define_promise(name, "@#{name}")
        end

        def define_promise(name, ivar)
          define_method(name) { get_or_set_promise(ivar) }
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hatetepe-0.6.0.pre.1 lib/hatetepe/promise.rb