Sha256: 29c4d6dc546864f37b1fa20d849f27c3e0c8543ee11679fcc4630e3b14a268cd

Contents?: true

Size: 1.83 KB

Versions: 1

Compression:

Stored size: 1.83 KB

Contents

# encoding: utf-8

module Attestor

  module Validations

    # Describes an item of validations' collection
    #
    # @api private
    class Item

      # @!scope class
      # @!method new(name, except: [], only: [])
      # Creates a named item with blacklist or whitelist of contexts
      #
      # @param  [#to_sym] name
      # @option [#to_sym, Array<#to_sym>] :except
      # @option [#to_sym, Array<#to_sym>] :only
      #
      # @return [Attestor::Collection::Item]

      # @private
      def initialize(name, except: nil, only: nil)
        @name      = name.to_sym
        @whitelist = normalize(only)
        @blacklist = normalize(except)
        generate_id
        freeze
      end

      # @!attribute [r] name
      # The name of the item
      # @return [Symbol]
      attr_reader :name

      # Compares an item to another one
      #
      # @param [Object] other
      #
      # @return [Boolean]
      def ==(other)
        other.instance_of?(self.class) ? id.equal?(other.id) : false
      end

      # Checks if the item should be used in given context
      #
      # @param [#to_sym] context
      #
      # @return [Boolean]
      def used_in_context?(context)
        symbol = context.to_sym
        whitelisted?(symbol) && !blacklisted?(symbol)
      end

      protected

      # @!attribute [r] id
      # The item's identity
      #
      # @return [String]
      attr_reader :id

      private

      attr_reader :whitelist, :blacklist

      def whitelisted?(symbol)
        whitelist.empty? || whitelist.include?(symbol)
      end

      def blacklisted?(symbol)
        blacklist.include? symbol
      end

      def generate_id
        @id = [name, whitelist, blacklist].hash
      end

      def normalize(list)
        Array(list).map(&:to_sym).uniq
      end

    end # class Item

  end # module Validations

end # module Attestor

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
attestor-0.0.1 lib/attestor/validations/item.rb