Sha256: 3a7fa216a5256e98cb878a5ffd60336c86d6ee1ed5cf4aa6bdb0e50437a48ee2

Contents?: true

Size: 1.5 KB

Versions: 14

Compression:

Stored size: 1.5 KB

Contents

# frozen_string_literal: true

class Serega
  module SeregaValidations
    #
    # Attribute parameters validators
    #
    module Attribute
      #
      # Attribute `block` parameter validator
      #
      class CheckBlock
        class << self
          #
          # Checks block parameter provided with attribute.
          # Must have up to two arguments - object and context.
          # It should not have any *rest or **key arguments
          #
          # @example without arguments
          #   attribute(:email) { CONSTANT_EMAIL }
          #
          # @example with one argument
          #   attribute(:email) { |obj| obj.confirmed_email }
          #
          # @example with two arguments
          #   attribute(:email) { |obj, context| context['is_current'] ? obj.email : nil }
          #
          # @param block [Proc] Block that returns serialized attribute value
          #
          # @raise [SeregaError] SeregaError that block has invalid arguments
          #
          # @return [void]
          #
          def call(block)
            return unless block

            check_block(block)
          end

          private

          def check_block(block)
            params = block.parameters
            return if (params.count <= 2) && params.all? { |par| par[0] == :opt }

            raise SeregaError, block_error
          end

          def block_error
            "Block can have maximum two regular parameters (no **keyword or *array args)"
          end
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

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