Sha256: 5730aa95ce3e6ae6384d7cbbdf14c407cf499f9c934f3432f3894ddbdd48f82e

Contents?: true

Size: 1.48 KB

Versions: 8

Compression:

Stored size: 1.48 KB

Contents

# frozen_string_literal: true

class Serega
  module SeregaValidations
    module Attribute
      class CheckBlock
        class << self
          #
          # Checks :value option or a block 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 opts [Proc] Attribute opts, we will check :value option
          # @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

8 entries across 8 versions & 1 rubygems

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