Sha256: 4760495e6e12838e175d2d3666d7b14bc4f4291b65f12a9ed28e494e0bdf7d2d

Contents?: true

Size: 1.09 KB

Versions: 2

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

require "set"

module Rekkyo
  module Type
    class << self
      def included(klass)
        klass.const_set(:Member, Class.new(Member))
        klass.instance_variable_set(:@members, Set.new)
        klass.extend(ClassMethods)
      end
    end

    module ClassMethods
      UNSPECIFIED = Object.new.freeze
      private_constant :UNSPECIFIED

      def member(key, value = UNSPECIFIED)
        value = key if value == UNSPECIFIED
        key = key.upcase.to_sym

        validate_member(key, value)

        self::Member.new(key, value).freeze.tap do |m|
          @members << m

          self.const_set(key, m)

          self::Member.class_exec do
            define_method(:"#{key.downcase}?") { self.match?(m) }
          end
        end
      end

      def all
        @members.dup
      end

      alias members all

      private

      def validate_member(key, value)
        raise DuplicateMemberError if self.const_defined?(key, false) ||
                                      @members.any? { |m| m.match? value }
      end
    end
  end
end

require "rekkyo/type/member"

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rekkyo-1.0.0 lib/rekkyo/type.rb
rekkyo-0.2.0 lib/rekkyo/type.rb