Module Poly::Owners
- Extended by: ActiveSupport::Concern
- Defined in: lib/poly/owners.rb
Write-time owner stamping: projects a resource’s root owner onto the row
itself (owner_type/owner_id by default) before validation, so ownership
queries need no traversal. Poly stamps; it never infers or enforces policy.
class Coin < ApplicationRecord belongs_to :resource, polymorphic: true include Poly::Owners poly_owner :resource, owner: -> { ledger.account }endPublic Class Methods
apply_owner
apply_owner(record, owner, type_column, id_column, allow_nil: true)Resolves owner for record and writes its type and id to the owner columns.
Called from the before_validation hook poly_owner installs.
- @param
record[ActiveRecord::Base] - @param
owner[Proc, Symbol, String, ActiveRecord::Base] seepoly_owner - @param
type_column[Symbol] - @param
id_column[Symbol] - @param
allow_nil[Boolean] - @raise [ArgumentError] if the owner is not a persisted ActiveRecord model,
or resolves to
nilwhileallow_nilis false - @return [void]
assign_nil_owner
assign_nil_owner(record, type_column, id_column, allow_nil:)Clears both owner columns, or raises if a nil owner is not allowed.
- @param
record[ActiveRecord::Base] - @param
type_column[Symbol] - @param
id_column[Symbol] - @param
allow_nil[Boolean] - @raise [ArgumentError] if
allow_nilis false - @return [void]
poly_owner
poly_owner(assoc_name, owner:, type_column: :owner_type, id_column: :owner_id, allow_nil: true, immutable: false)rubocop:disable Layout/LineLength rubocop:enable Layout/LineLength Declares owner columns populated before validation.
poly_owner :resource, owner: -> { ledger.account } poly_owner :resource, owner: :account@param assoc_name [Symbol] a polymorphic `belongs_to` declared on this model@param owner [Proc, Symbol, String, ActiveRecord::Base] a lambda evaluated on the record, a method name sent to it, or the owner itself@param type_column [Symbol] column receiving the owner's base class name@param id_column [Symbol] column receiving the owner's id@param allow_nil [Boolean] permit the owner to resolve to `nil`@param immutable [Boolean] reject owner changes once persisted@raise [ArgumentError] if `owner` is nil or `assoc_name` is not a polymorphic `belongs_to`@return [void]resolve_owner
resolve_owner(record, owner)Evaluates a poly_owner owner: spec against record: Procs are
instance-exec’d, Symbols/Strings are sent as method names, anything else is
returned as-is.
- @param
record[ActiveRecord::Base] - @param
owner[Proc, Symbol, String, Object] - @return [Object, nil]