Module: Stannum::Entities::PrimaryKey::ClassMethods

Defined in:
lib/stannum/entities/primary_key.rb

Overview

Class methods to extend the class when including PrimaryKey.

Instance Method Summary collapse

Instance Method Details

#define_primary_key(attr_name, attr_type, **options) ⇒ Symbol

Defines a primary key attribute on the entity.

Options Hash (**options):

  • :default (Object)

    The default value for the attribute. Defaults to nil.

  • :primary_key (Boolean)

    true if the attribute represents the primary key for the entity; otherwise false. Defaults to false.

See Also:

  • Attributes::ClassMethods#define_attribute.

Parameters:

  • The name of the attribute. Must be a non-empty String or Symbol.

  • The type of the attribute. Must be a Class or Module, or the name of a class or module.

  • Additional options for the attribute.

Returns:

  • The attribute name as a symbol.



32
33
34
35
36
37
38
39
# File 'lib/stannum/entities/primary_key.rb', line 32

def define_primary_key(attr_name, attr_type, **options)
  if primary_key?
    raise PrimaryKeyAlreadyExists,
      "#{name} already defines primary key #{primary_key_name.inspect}"
  end

  attribute(attr_name, attr_type, **options, primary_key: true)
end

#primary_keyStannum::Attribute

Returns the primary key attribute.

Raises:

  • if the entity does not define a primary key.

Returns:

  • the primary key attribute.



45
46
47
48
49
50
51
52
53
54
# File 'lib/stannum/entities/primary_key.rb', line 45

def primary_key
  primary_key =
    attributes
    .find { |_, attribute| attribute.primary_key? }
    &.last

  return primary_key if primary_key

  raise PrimaryKeyMissing, "#{name} does not define a primary key"
end

#primary_key?Boolean

Returns true if the entity class defines a primary key; otherwise false.

Returns:

  • true if the entity class defines a primary key; otherwise false.



58
59
60
# File 'lib/stannum/entities/primary_key.rb', line 58

def primary_key?
  attributes.any? { |_, attribute| attribute.primary_key? }
end

#primary_key_nameString?

Returns the name of the primary key attribute, or nil if the entity does not define a primary key.

Returns:

  • the name of the primary key attribute, or nil if the entity does not define a primary key.



64
65
66
67
68
69
# File 'lib/stannum/entities/primary_key.rb', line 64

def primary_key_name
  attributes
    .find { |_, attribute| attribute.primary_key? }
    &.last
    &.name
end

#primary_key_typeClass?

Returns the type of the primary key attribute, or nil if the entity does not define a primary key.

Returns:

  • the type of the primary key attribute, or nil if the entity does not define a primary key.



73
74
75
76
77
78
# File 'lib/stannum/entities/primary_key.rb', line 73

def primary_key_type
  attributes
    .find { |_, attribute| attribute.primary_key? }
    &.last
    &.resolved_type
end