Sha256: 99f7a4778213770e2e5410e9fa152904d6fe0dcff882142531bbee1285bd7f62

Contents?: true

Size: 1.21 KB

Versions: 2

Compression:

Stored size: 1.21 KB

Contents

# frozen_string_literal: true

module DirtySeed
  module Assigners
    # Manages assignment when value should be included in an enumerable
    class Inclusion < Assigner
      # Returns a random value matching validators
      # @return [Object] a "primitive"
      def value
        return unless respond?

        case options
        when Array then options.sample
        when Range then rand(options)
        end
      end

      # Should be the value included in options?
      # @return [Boolean]
      def respond?
        @respond ||= options.present?
      end

      private

      # Returns the inclusion options if value should be included in options
      # @return [Array, Range]
      # @example
      #   ["todo", "done", "aborted"]
      #   0..10
      def options
        @options ||= enum || inclusion_validator&.options&.dig(:in)
      end

      # Returns the inclusion validator if any
      #   e.g. `validates :status, inclusion: { in: ["todo", "done", "aborted"] }`
      # @return [ActiveModel::Validations::InclusionValidator, nil]
      def inclusion_validator
        validators&.find do |validator|
          validator.is_a? ActiveModel::Validations::InclusionValidator
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dirty_seed-0.2.1 lib/dirty_seed/assigners/inclusion.rb
dirty_seed-0.2.0 lib/dirty_seed/assigners/inclusion.rb