Sha256: 6219ee44ffec8eb8e40248debc8200b64d67fb002b104be8d380e3392a5e909d

Contents?: true

Size: 1.63 KB

Versions: 13

Compression:

Stored size: 1.63 KB

Contents

# frozen_string_literal: true

class Serega
  module SeregaValidations
    module Attribute
      #
      # Attribute `:value` option validator
      #
      class CheckOptValue
        class << self
          #
          # Checks attribute :value option
          #
          # @param opts [Hash] Attribute options
          #
          # @raise [SeregaError] SeregaError that option has invalid value
          #
          # @return [void]
          #
          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

13 entries across 13 versions & 1 rubygems

Version Path
serega-0.15.0 lib/serega/validations/attribute/check_opt_value.rb
serega-0.14.0 lib/serega/validations/attribute/check_opt_value.rb
serega-0.12.0 lib/serega/validations/attribute/check_opt_value.rb
serega-0.11.2 lib/serega/validations/attribute/check_opt_value.rb
serega-0.11.1 lib/serega/validations/attribute/check_opt_value.rb
serega-0.11.0 lib/serega/validations/attribute/check_opt_value.rb
serega-0.10.0 lib/serega/validations/attribute/check_opt_value.rb
serega-0.9.0 lib/serega/validations/attribute/check_opt_value.rb
serega-0.8.3 lib/serega/validations/attribute/check_opt_value.rb
serega-0.8.2 lib/serega/validations/attribute/check_opt_value.rb
serega-0.8.1 lib/serega/validations/attribute/check_opt_value.rb
serega-0.8.0 lib/serega/validations/attribute/check_opt_value.rb
serega-0.7.0 lib/serega/validations/attribute/check_opt_value.rb