Sha256: d2596ca330851d9dfe7413a4349b501a0ef3d21697418b5010509390f99b6ac8

Contents?: true

Size: 931 Bytes

Versions: 1

Compression:

Stored size: 931 Bytes

Contents

require "kontext/version"

begin
  require "fiber"
rescue LoadError => ex
  raise(ex) unless ex.message =~ /fiber/
end

class Kontext
  RootFiber = defined?(::Fiber) ? Fiber.current : nil

  def thread?
    Thread.current != Thread.main
  end

  def fiber?
    defined?(::Fiber) && Fiber.current != RootFiber
  end

  def store
    if fiber?
      # TODO over time this will leak massively
      Thread.current[Fiber.current.object_id.to_s] ||= {}
    elsif thread?
      Thread.current
    else
      @store ||= {}
    end
  end

  def stack
    store[self] ||= []
  end

  def with(obj)
    old_size = size
    push(obj)

    begin
      result = yield(obj)
    ensure
      truncate(old_size)
    end

    result
  end

  def push(obj)
    stack.push(obj)
  end

  def pop
    stack.pop
  end

  def last
    stack.last
  end

  def size
    stack.length
  end

  def truncate(new_size)
    pop until size == new_size
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
kontext-0.1.1 lib/kontext.rb