Module: SolidAgent::Records::Ownable

Extended by:
ActiveSupport::Concern
Included in:
Agent
Defined in:
lib/solid_agent/records/ownable.rb

Overview

Configurable ownership for the agent records.

Tenancy is the one thing every application has already decided before it installs this gem. The platform scopes agents to a plain user_id; a multi-tenant host scopes them to an account, a workspace, an organization. Hardcoding belongs_to :user would force one of those to migrate, and hardcoding nothing would leave every consumer to reinvent the same scope.

So the concern declares the association from two class attributes, and everything else in the gem talks to it through the owner pair — which is why AgentTemplate#create_agent_for can assign an owner it knows nothing about.

The belongs_to is declared with a class name, never a class: host models are autoloaded, and constantizing User while the gem's concern is being included either deadlocks the Rails loader or pins a class that the next code reload replaces. It is also optional: true, because a single-user install legitimately has agents that belong to nobody.

Examples:

The default: agents own a user_id column

class Agent < ApplicationRecord
  include SolidAgent::Records::Ownable
end

agent.owner = current_user
Agent.for_owner(current_user)

A multi-tenant host

class Agent < ApplicationRecord
  include SolidAgent::Records::Ownable
  owned_by :account, class_name: "Tenancy::Account"
end

Agent.owner_foreign_key #=> "account_id"

Instance Method Summary collapse

Instance Method Details

#ownerObject?

The record this one belongs to, or nil when the host stores no owner.

Defined as a method rather than alias_method because the underlying association is per-class configuration: an alias would bind to whatever owned_by had been called with at include time, and a subclass that re-owned itself would silently keep reading the parent's association.

Returns:

  • (Object, nil)


117
118
119
120
121
# File 'lib/solid_agent/records/ownable.rb', line 117

def owner
  return nil unless self.class.owner_column?

  public_send(self.class.owner_association)
end

#owner=(record) ⇒ Object?

Returns the assigned record.

Parameters:

  • record (Object, nil)

    the owning record

Returns:

  • (Object, nil)

    the assigned record



125
126
127
# File 'lib/solid_agent/records/ownable.rb', line 125

def owner=(record)
  public_send(:"#{self.class.owner_association}=", record)
end