Sha256: 6ab09b2717cd5861d815cf0379e0236b511f974c6543e9aa990d7f8e124fc7c2

Contents?: true

Size: 1.63 KB

Versions: 1

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 :method" if opts.key?(:method)
            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

1 entries across 1 versions & 1 rubygems

Version Path
serega-0.16.0 lib/serega/validations/attribute/check_opt_value.rb