Sha256: 33976da4345ecb5e834ac2f307f4b7c2d524b9f9ee4565ba29c0983d799c6994

Contents?: true

Size: 1.55 KB

Versions: 8

Compression:

Stored size: 1.55 KB

Contents

# frozen_string_literal: true

class Serega
  module SeregaValidations
    module Attribute
      class CheckOptValue
        #
        # Checks attribute :value option
        #
        # @param opts [Hash] Attribute options
        #
        # @raise [SeregaError] SeregaError that option has invalid value
        #
        # @return [void]
        #
        class << self
          def call(opts, block = nil)
            return unless opts.key?(:value)

            check_usage_with_other_params(opts, block)
            check_proc(opts[:value])
          end

          private

          def check_usage_with_other_params(opts, block)
            raise SeregaError, "Option :value can not be used together with option :key" if opts.key?(:key)
            raise SeregaError, "Option :value can not be used together with option :const" if opts.key?(:const)
            raise SeregaError, "Option :value can not be used together with block" if block
          end

          def check_proc(value)
            raise SeregaError, value_error unless value.is_a?(Proc)

            params = value.parameters

            if value.lambda?
              return if (params.count == 2) && params.all? { |par| par[0] == :req }
            elsif (params.count <= 2) && params.all? { |par| par[0] == :opt }
              return
            end

            raise SeregaError, value_error
          end

          def value_error
            "Option :value must be a Proc that is able to accept two parameters (no **keyword or *array args)"
          end
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
serega-0.6.1 lib/serega/validations/attribute/check_opt_value.rb
serega-0.6.0 lib/serega/validations/attribute/check_opt_value.rb
serega-0.5.2 lib/serega/validations/attribute/check_opt_value.rb
serega-0.5.1 lib/serega/validations/attribute/check_opt_value.rb
serega-0.5.0 lib/serega/validations/attribute/check_opt_value.rb
serega-0.4.0 lib/serega/validations/attribute/check_opt_value.rb
serega-0.3.0 lib/serega/validations/attribute/check_opt_value.rb
serega-0.2.0 lib/serega/validations/attribute/check_opt_value.rb