Sha256: 72adf2868f78d7d8ad4fe8a7988955cbfe443823e0ab4f1310b50402c93ec6d9

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

# encoding: utf-8

class MQ
  # MQ::Collection is used to store named AMQ model entities (exchanges, queues)
  class Collection < ::Array
    class IncompatibleItemError < ArgumentError
      def initialize(item)
        super("Instance of #{item.class} doesn't respond to #name!")
      end
    end

    def [](name)
      self.find do |object|
        object.name == name
      end
    end

    # Collection#[]= doesn't really make any sense, as we can't
    # redefine already existing Queues and Exchanges (we can declare
    # them multiple times, but if the queue resp. exchange is already
    # in the collection, it doesn't make sense to do so and we can't
    # run declare twice in order to change options, because the AMQP
    # broker closes the connection if we try to do so).

    # Use Collection# << for adding items to the collection.
    undef_method :[]=

    def <<(item)
      if (item.name rescue nil).nil? || !self[item.name]
        self.add!(item)
      end

      # We can't just return the item, because in case the item isn't added
      # to the collection, then it'd be different from self[item.name].
      return self[item.name]
    end

    alias_method :__push__, :push
    alias_method :push, :<<

    def add!(item)
      unless item.respond_to?(:name)
        raise IncompatibleItemError.new(item)
      end

      __push__(item)
      return item
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
amqp-0.7.0 lib/mq/collection.rb