03 · Permissify — examples
Status: Reference · Gem: StockLive-Group/permissify ·
API docs (RDoc): kuickr.co/stocklive/permissify-api
This mirrors the gem's canonical
EXAMPLES.md. Every example maps to behavior covered by the gem's tests (test/permissify_test.rb,test/scope_and_fact_source_test.rb). See the authorization contract for the design and the Pundit-eradication plan for the migration.
Permissify answers one question — can this actor perform this action on this
resource? — and returns one explicit, observable Decision. It is default-deny,
has no superuser bypass, no generated ":#{action}able" fallback, and needs no framework.
1. Defining a resource
A resource is a bundle of named facts, permissions that compose those facts, and actions that alias to a permission. The DSL is evaluated at boot.
Permissify.define(:article) do
fact(:draft) { |ctx| ctx.resource.status == "draft" }
fact(:owned) { |ctx| ctx.resource.user_id == ctx.actor.id }
permission(:editable) { |ctx| ctx.all?(:draft, :owned) }
action :edit, maps_to: :editable
action :update, maps_to: :editable
end
-
factblocks receive aDecisionContextand return a boolean. -
permissionblocks read facts via combinators. -
action ..., maps_to:is the only way an action resolves to a permission — there is no implicit":#{action}able"naming convention. - Duplicate fact / permission / action / scope names raise
DefinitionErrorat boot.
2. Making a decision
Permissify.decide(actor: author, action: :edit, resource: article, resource_key: :article).allowed? # => true
Permissify.decide(actor: stranger, action: :edit, resource: article, resource_key: :article).allowed? # => false
resource_key selects the definition; resource is the object under test; action is
the verb. All four keywords are required.
3. The Decision object
decide always returns an immutable Decision — never a bare boolean, never nil.
decision = Permissify.decide(actor: author, action: :edit, resource: article, resource_key: :article)
decision.allowed? # => true
decision.denied? # => false
decision.permission # => :editable
decision.reason # => :allowed (or :denied, :unknown_action, :missing_fact, …)
decision.checks # => [{ name: :draft, result: true }, { name: :owned, result: true }]
decision.metadata # => { resource_key: :article, action: :edit }
decision.to_h # => { allowed:, permission:, reason:, checks:, metadata: }
The reason distinguishes an ordinary policy :denied from a structural denial
(:unknown_resource, :unknown_action, :unknown_permission, :missing_fact,
:fact_error) — so a "no" is always explainable.
4. Boolean projection — allow?
Permissify.allow?(actor: author, action: :edit, resource: article, resource_key: :article) # => true
allow? is exactly decide(...).allowed? — same arguments, same safety contract.
5. Enforcement — authorize!
Raise on deny at an enforcement boundary; the Decision is attached to the error.
begin
Permissify.authorize!(actor: stranger, action: :edit, resource: article, resource_key: :article)
rescue Permissify::NotAuthorized => e
e.decision.reason # => :denied
e.decision.permission # => :editable
end
On allow, authorize! returns the Decision.
6. Combinators — all? / any? / none?
Inside a permission, read facts through combinators; each call is recorded in
decision.checks.
permission(:viewable) { |ctx| ctx.any?(:published, :owner) }
permission(:editable) { |ctx| ctx.all?(:owner) && ctx.none?(:locked) }
-
all?(*facts)— every fact true.any?(*facts)— at least one true.none?(*facts)— all false. - Facts are memoized per decision, so referencing the same fact twice evaluates it once.
7. Environment
Pass request- or tenant-scoped context without stuffing it onto the actor or resource.
fact(:same_tenant) { |ctx| ctx.resource.tenant_id == ctx.environment[:tenant_id] }
Permissify.decide(actor: user, action: :show, resource: report,
resource_key: :report, environment: { tenant_id: 42 })
8. Authorized scopes — authorization as a query
For collections, never filter in Ruby. Register a scope builder and let the database do
the narrowing. A missing scope raises NoScope — it never returns every row.
Permissify.define(:article) do
permission(:viewable) { |_ctx| true }
action :index, maps_to: :viewable
scope(:viewable) { |actor, relation, _env| relation.where(user_id: actor.id) }
end
Permissify.authorized_scope(actor: current_user, action: :index,
relation: Article.all, resource_key: :article)
# => Article.where(user_id: current_user.id)
relation is anything the host passes — an ActiveRecord relation in Rails, or a plain
Array in a test — so the port stays framework-free.
9. The FactSource port
Facts don't have to be inline. A FactSource supplies them externally, and the same
permission yields the same decision whether a fact is inline or sourced.
class MyFactSource
def fetch(name, ctx)
return ctx.resource[:owner_id] == ctx.actor[:id] if name == :owned
Permissify::FactSource::Missing # this source can't answer that fact
end
end
Permissify.decide(actor: { id: 7 }, action: :edit, resource: { owner_id: 7 },
resource_key: :doc, fact_source: MyFactSource.new).allowed? # => true
The default FactSource::Null returns Missing for everything; a fact that is neither
inline nor sourced raises MissingFact, which denies with reason :missing_fact.
10. Safety contracts
Everything unknown, and every evaluation error, denies — observably.
Permissify.decide(actor: u, action: :edit, resource: r, resource_key: :nope).reason # => :unknown_resource
Permissify.decide(actor: u, action: :teleport, resource: r, resource_key: :article).reason # => :unknown_action
# a fact that raises denies with reason :fact_error — it does not blow up the request
No superuser bypass, no ":#{action}able" fallback — an action only resolves through an
explicit action ..., maps_to: mapping.
11. Migrating a Pundit policy
Pundit is data-modelled (one policy per record, a method per action, role checks repeated). Permissify is domain-modelled (named facts and permissions, composed once).
# BEFORE — Pundit: 14 methods, two repeated role checks
class ContactPolicy < ApplicationPolicy
def index? = user.assessor?
def destroy? = user.assessor? && user.staff?
def approve? = user.assessor? && user.staff?
class Scope < Scope
def resolve = scope.where(user: user)
end
end
# AFTER — Permissify: two facts, two permissions, explicit aliases + scope
Permissify.define(:contact) do
fact(:assessor) { |ctx| ctx.actor.assessor? }
fact(:staff) { |ctx| ctx.actor.staff? }
permission(:viewable) { |ctx| ctx.all?(:assessor) }
permission(:manageable) { |ctx| ctx.all?(:assessor, :staff) }
action :index, maps_to: :viewable
action :destroy, maps_to: :manageable
action :approve, maps_to: :manageable
scope(:viewable) { |actor, relation, _env| relation.where(user: actor) }
end
The full gallery and phased plan are in 02 — Pundit eradication.
12. Optional Predicate as a domain-fact source
Permissify needs no other library. But where a domain-validity rule already lives in Predicate — stable facts safe to memoize — Permissify can read its result as a plain fact. Authorization stays fresh; the domain rule stays where it belongs.
Predicate.define(:article) do
content_complete { |s| is_present?(s[:title]) && is_present?(s[:body]) && s[:media_ids].any? }
end
Permissify.define(:article) do
fact(:complete) do |ctx|
Predicate.for(:article).call(:content_complete,
title: ctx.resource.title, body: ctx.resource.body, media_ids: ctx.resource.media_ids)
end
fact(:owner) { |ctx| ctx.resource.user_id == ctx.actor.id }
permission(:publishable) { |ctx| ctx.all?(:owner, :complete) }
action :publish, maps_to: :publishable
end
Predicate is an optional domain layer beneath authorization — never a required dependency, and never the store for volatile authz facts (those stay plain Ruby, and fresh).
13. Rails integration
The core needs no framework. require "permissify/rails" adds an optional controller
concern — no runtime dependency, nothing added to the core.
class ApplicationController < ActionController::Base
include Permissify::Controller
verify_permissify_authorized # fail loud if an action forgot to authorize
rescue_from Permissify::NotAuthorized, with: :forbidden
end
class ContactsController < ApplicationController
def show
@contact = permissify_authorize(Contact.find(params[:id])) # raises on deny
end
def index
@contacts = permissify_scope(Contact.all) # DB-level narrowing
end
end
-
permissify_authorize(resource, action:, resource_key:, environment:)— returns the resource on allow, raisesNotAuthorizedon deny.actiondefaults toaction_name;resource_keyis inferred from the model name (Contact→:contact) unless given. -
permissify_scope(relation, …)— delegates toauthorized_scope; raisesNoScopewhen the resource has no registered scope. -
verify_permissify_authorized/verify_permissify_scoped— after_action guards so a forgotten authorization fails loud, never open. - Override
permissify_actor(defaults tocurrent_user) andpermissify_environment(defaults to{}) for the subject and tenant/request context.
The names are deliberately distinct from Pundit's so both can run side by side during the shadow migration (see 02 — Pundit eradication).
14. Sourcing many domain facts — PredicateFactSource
Section 12 reads a single Predicate result inline. When several stable domain facts come
from one Predicate entity, require "permissify/predicate" and wire them through the
FactSource port instead of a block per fact.
source = Permissify::PredicateFactSource.new(
entity: Predicate.for(:article), # responds to call(name, state) -> boolean
facts: [:content_complete],
state: ->(ctx) { { title: ctx.resource.title, body: ctx.resource.body,
media_ids: ctx.resource.media_ids } }
)
Permissify.define(:article) do
fact(:owner) { |ctx| ctx.resource.user_id == ctx.actor.id } # volatile → inline, fresh
permission(:publishable) { |ctx| ctx.all?(:owner, :content_complete) }
action :publish, maps_to: :publishable
end
Permissify.decide(actor: user, action: :publish, resource: article,
resource_key: :article, fact_source: source)
-
facts:declares exactly which names this source owns; any other name returnsMissing, so inline facts and other sources still win. - An owned fact whose entity raises denies with
:fact_error; one neither inline nor owned denies with:missing_fact— never a silent allow. - The entity is injected → no load-time dependency on the
predicategem.
Stable facts only. Predicate always memoizes, so volatile authorization facts (roles, ownership) stay inline and fresh. Predicate is a domain layer beneath authorization.