Sha256: d5b99544b5115e59a1e364a8f873a0ee684e8e814fba707e2aa5aa82277fa717

Contents?: true

Size: 1.14 KB

Versions: 3

Compression:

Stored size: 1.14 KB

Contents

module Indexable
  attr_accessor :index_number  # attr_reader_once_write instead?
  attr_accessor :factory
end

class IndexableFactory
  attr_reader :instances, :start_index, :next_index
  
  def initialize(klass, startIndex = 0)
    unless klass.ancestors.include?(Indexable)
      raise ArgumentError, "#{klass.inspect} is not Indexable" 
    end
    @klass, @start_index, @next_index = klass, startIndex, startIndex
    @instance_map, @instances = Hash.new, Array.new
  end

  def make(*args)
    obj = @instance_map[args]
    unless obj
      @instance_map[args] = obj = make_new_obj(args)
      @instances.push obj
    end
    obj
  end

  def make_unless_exists(*args)
    new_instance = @instance_map[args] == nil
    return make(*args), new_instance
  end

  def get_instance(*args)
    @instance_map[args]
  end

  def instance_with_args(*args)
    @instance_map[args] || (@instance_map[args] = make(*args))
  end

  protected

  def make_new_obj(arguments)
    obj = @klass.new(*arguments)
    obj.index_number = advance_index_number
    obj.factory = self
    obj
  end
  
  def advance_index_number
    i = @next_index
    @next_index += 1
    i
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rpdf2txt-0.8.4 lib/rpdf2txt-rockit/indexable.rb
rpdf2txt-0.8.3 lib/rpdf2txt-rockit/indexable.rb
rpdf2txt-0.8.2 lib/rpdf2txt-rockit/indexable.rb