Bandera.Constraint (bandera v0.4.0)

Copy Markdown View Source

A single targeting predicate evaluated against an evaluation context.

Context values often arrive as strings (JSON bodies, query params, headers), so equality, membership, and ordering operators coerce numeric strings to numbers before comparing — %{"age" => "20"} does satisfy {"age", :gte, 18} because "20" coerces to 20. Ordering between a number and a non-numeric string fails closed (no match). A missing attribute never matches. :matches is an unanchored regex, so {"role", :matches, "admin"} also matches "superadmin"; anchor with ^/$ if you need a full-string match.

Summary

Functions

Returns true when the constraint matches the given evaluation context map.

Builds a constraint for attribute using operator and value.

Types

t()

@type t() :: %Bandera.Constraint{
  attribute: String.t(),
  operator: atom(),
  values: [term()]
}

Functions

match?(constraint, context)

@spec match?(t(), map()) :: boolean()

Returns true when the constraint matches the given evaluation context map.

The context map uses string keys. A missing key never matches. Numeric strings are coerced to numbers before comparison (see the module doc).

Examples

iex> c = Bandera.Constraint.new("age", :gte, 18)
iex> Bandera.Constraint.match?(c, %{"age" => "20"})
true

iex> Bandera.Constraint.match?(c, %{"age" => "15"})
false

iex> Bandera.Constraint.match?(c, %{})
false

new(attribute, operator, values)

@spec new(String.t(), atom(), term()) :: t()

Builds a constraint for attribute using operator and value.

operator must be one of :eq, :neq, :in, :not_in, :contains, :gt, :gte, :lt, :lte, or :matches. For list operators (:in, :not_in) pass a list as value; for all others a single scalar. Scalars are wrapped in a list internally.

Examples

iex> c = Bandera.Constraint.new("plan", :eq, "premium")
iex> Bandera.Constraint.match?(c, %{"plan" => "premium"})
true