Module: Castkit::Core::Registerable

Included in:
Castkit::Contract::Generic, DataObject
Defined in:
lib/castkit/core/registerable.rb

Overview

Provides methods to register dynamically generated contracts and data objects into the appropriate Castkit namespaces (‘Castkit::Contracts`, `Castkit::DataObjects`).

This is useful when working with ephemeral classes (e.g., from ‘Contract.build` or `.to_dataobject`) that should be persisted and referenced as constants.

Examples:

Registering a contract class

contract = Castkit::Contract.build(:user) { string :id }
contract.extend(Castkit::Core::Registerable)
contract.register! # => Castkit::Contracts::User

Registering a DTO

dto = contract.to_dataobject
dto.extend(Castkit::Core::Registerable)
dto.register!(as: :UserDto) # => Castkit::DataObjects::UserDto

Constant Summary collapse

CASTKIT_NAMESPACES =
{
  contracts: Castkit::Contracts,
  dataobjects: Castkit::DataObjects
}.freeze

Instance Method Summary collapse

Instance Method Details

#register!(namespace:, as: nil) ⇒ Class

Registers the current class in the specified Castkit namespace.

Parameters:

  • namespace (Symbol)

    ‘:contracts` or `:dataobjects`

  • as (String, Symbol, nil) (defaults to: nil)

    Optional constant name override (PascalCase). If not provided, falls back to the class’s name (via ‘Inflector.pascalize(self.name)`).

Returns:

  • (Class)

    the registered class

Raises:

  • (Castkit::Error)

    if class is anonymous or name already exists in the namespace



36
37
38
39
40
41
42
43
44
45
# File 'lib/castkit/core/registerable.rb', line 36

def register!(namespace:, as: nil)
  name = Castkit::Inflector.pascalize(as || self.name)
  raise Castkit::Error, "Unable to register anonymous classes, use as: ClassName" if name.nil?

  ns = Castkit.const_get(namespace.to_s.capitalize, false)
  raise Castkit::Error, "#{name} is already registered in #{ns}" if defined_in_namespace?(ns, name)

  ns.const_set(name, self)
  self
end