lib/multicodecs/registry.rb in multicodecs-0.1.0 vs lib/multicodecs/registry.rb in multicodecs-0.2.0
- old
+ new
@@ -1,10 +1,18 @@
# frozen_string_literal: true
module Multicodecs
+ class AutoHashCollection < Hash
+ def [](key)
+ self[key] = [] unless key?(key)
+ super
+ end
+ end
+
# rubocop:disable Style/MutableConstant
REGISTRATIONS = {}
+ REGISTRATIONS_PER_TAG = AutoHashCollection.new
# rubocop:enable Style/MutableConstant
Registration = Struct.new(:code, :name, :tag) do
def hash
name.hash
@@ -27,15 +35,14 @@
def [](entry)
find_by(code: entry, name: entry)
end
def register(code:, name:, tag:)
- Multicodecs::REGISTRATIONS[name] = Registration.new(
- code,
- name,
- tag
- )
+ Registration.new(code, name, tag).tap do |registration|
+ Multicodecs::REGISTRATIONS[name] = registration
+ Multicodecs::REGISTRATIONS_PER_TAG[tag] << registration
+ end
end
def fetch_by!(code: nil, name: nil)
return Multicodecs::REGISTRATIONS.fetch(name) if name
@@ -54,7 +61,25 @@
Multicodecs::REGISTRATIONS.values.map(&:code)
end
def names
Multicodecs::REGISTRATIONS.keys
+ end
+
+ def tags
+ Multicodecs::REGISTRATIONS_PER_TAG.keys
+ end
+
+ def where(tag:)
+ Multicodecs::REGISTRATIONS_PER_TAG[tag]
+ end
+
+ def each(tag: nil)
+ arr = tag.nil? ? Multicodecs::REGISTRATIONS.values : Multicodecs.where(tag: tag)
+
+ if block_given?
+ return arr.each { |registration| yield registration }
+ end
+
+ arr.each
end
end