Sha256: 3e8f050242480012e13b692db8d627bc73ff35b9b9e1421c49cc95ad14beebfa

Contents?: true

Size: 982 Bytes

Versions: 4

Compression:

Stored size: 982 Bytes

Contents

module ToFactory
  class CannotInferClass < ArgumentError
    def initialize(message)
      super message.inspect
    end
  end

  class KlassInference
    def initialize(representations)
      @mapping = {}

      representations.each do |r|
        set_mapping_from(r)
      end
    end

    def infer(factory_name, count=0)
      count = count + 1
      result  = @mapping[factory_name]
      return [result, count] if result.is_a? Class

      if result.nil?
        raise CannotInferClass.new(factory_name)
      end

      infer(result, count)
    end

    private

    def set_mapping_from(r)
      if parent_klass = to_const(r.parent_name)
        @mapping[r.parent_name] = parent_klass
      end

      @mapping[r.name] =
        if factory_klass = to_const(r.name)
          factory_klass
        else
          r.parent_name
        end
    end

    def to_const(factory_name)
      factory_name.to_s.camelize.constantize
    rescue NameError
      nil
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
to_factory-2.1.0 lib/to_factory/klass_inference.rb
to_factory-2.0.0 lib/to_factory/klass_inference.rb
to_factory-0.2.1 lib/to_factory/klass_inference.rb
to_factory-0.2.0 lib/to_factory/klass_inference.rb