philiprehberger-guard_clause

Tests Gem Version License

Expressive guard clause DSL for method precondition validation

Requirements

  • Ruby >= 3.1

Installation

Add to your Gemfile:

gem "philiprehberger-guard_clause"

Or install directly:

gem install philiprehberger-guard_clause

Usage

require 'philiprehberger/guard_clause'

Philiprehberger::GuardClause.guard(name).not_nil('name is required').not_empty
Philiprehberger::GuardClause.guard(age).not_nil.positive.gte(18)

Chaining Guards

Philiprehberger::GuardClause.guard(price)
  .not_nil('price is required')
  .positive('price must be positive')
  .lte(10_000, 'price exceeds maximum')

Regex Matching

Philiprehberger::GuardClause.guard(email).matches(/@/, 'invalid email format')

Inclusion Check

Philiprehberger::GuardClause.guard(role).one_of(%i[admin user guest], 'invalid role')

Soft Mode

Collect all errors without raising:

guard = Philiprehberger::GuardClause.guard(value, soft: true)
guard.not_nil.not_empty.positive

guard.valid?   # => false
guard.errors   # => ['value must not be empty', 'value must be positive']

API

Method Description
GuardClause.guard(value, soft: false) Create a guard for the given value
#not_nil(msg) Assert value is not nil
#not_empty(msg) Assert value is not empty
#positive(msg) Assert value is positive
#gte(n, msg) Assert value >= n
#lte(n, msg) Assert value <= n
#matches(regex, msg) Assert value matches pattern
#one_of(arr, msg) Assert value is in the list
#not_equal(other, msg) Assert value differs from other
#value Return the guarded value
#valid? Return true if no errors (soft mode)
#errors Return collected errors (soft mode)

Development

bundle install
bundle exec rspec
bundle exec rubocop

License

MIT