Sha256: 8d93ff1748912a8a2d48c788a5751f80bd1fa14dce64cec7494987774aabc976

Contents?: true

Size: 927 Bytes

Versions: 1

Compression:

Stored size: 927 Bytes

Contents

require "kontext/version"

begin
  require "fiber"
rescue LoadError => ex
  raise(ex) if 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.0 lib/kontext.rb