Sha256: 937d68ed291fb4af0ba2e336c7ee15b10a20b5ecdf2dd316ea02523d4433c660

Contents?: true

Size: 1.32 KB

Versions: 22

Compression:

Stored size: 1.32 KB

Contents

module Riveter
  module AssociatedTypeRegistry
    extend ActiveSupport::Concern

    included do
      container = self
      type_registry = TypeRegistry.new()

      define_singleton_method :container do
        container
      end

      define_singleton_method :registry do
        type_registry
      end
    end

    module ClassMethods
      def key_for(type)
        type.is_a?(Symbol) ? type : type.name.underscore.to_sym
      end

      def register_type(type, associated_type, options={})
        options = {
          :key => key_for(associated_type)
        }.merge(options)

        # prevent duplicate registrations
        type_list = container.registry[options[:key]]
        type_list << type unless type_list.include?(type)
      end

      def resolve!(type)
        registered = self.resolve(type)
        raise UnregisteredTypeError.new(type) unless registered
        registered
      end

      def resolve(type)
        self.resolve_all(type).first
      end

      def resolve_all(type)
        container.registry[key_for(type)] || []
      end
    end
  end

  class TypeRegistry < Hash
    def initialize
      super {|h, k| h[k] = []}
    end
  end

  class UnregisteredTypeError < StandardError
    attr_reader :type

    def initialize(type)
      super "Unregistered type '#{type}'"
      @type = type
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
riveter-0.8.3 lib/riveter/associated_type_registry.rb
riveter-0.8.2 lib/riveter/associated_type_registry.rb
riveter-0.8.1 lib/riveter/associated_type_registry.rb
riveter-0.8.0 lib/riveter/associated_type_registry.rb
riveter-0.7.0 lib/riveter/associated_type_registry.rb
riveter-0.6.0 lib/riveter/associated_type_registry.rb
riveter-0.3.0 lib/riveter/associated_type_registry.rb
riveter-0.2.1 lib/riveter/associated_type_registry.rb
riveter-0.2.0 lib/riveter/associated_type_registry.rb
riveter-0.1.1 lib/riveter/associated_type_registry.rb
riveter-0.0.15 lib/riveter/associated_type_registry.rb
riveter-0.0.14 lib/riveter/associated_type_registry.rb
riveter-0.0.13 lib/riveter/associated_type_registry.rb
riveter-0.0.12 lib/riveter/associated_type_registry.rb
riveter-0.0.11 lib/riveter/associated_type_registry.rb
riveter-0.0.10 lib/riveter/associated_type_registry.rb
riveter-0.0.9 lib/riveter/associated_type_registry.rb
riveter-0.0.8 lib/riveter/associated_type_registry.rb
riveter-0.0.7 lib/riveter/associated_type_registry.rb
riveter-0.0.6 lib/riveter/associated_type_registry.rb