Class: Apiwork::Representation::Inheritance

Inherits:
Object
  • Object
show all
Defined in:
lib/apiwork/representation/inheritance.rb

Overview

Tracks STI subclass representations for a base representation.

Created automatically when a representation’s model uses STI. Provides resolution of records to their correct subclass representation.

Examples:

ClientRepresentation.inheritance.column # => :type
ClientRepresentation.inheritance.subclasses # => [PersonClientRepresentation, ...]
ClientRepresentation.inheritance.resolve(record) # => PersonClientRepresentation

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_class) ⇒ Inheritance

Returns a new instance of Inheritance.



29
30
31
32
# File 'lib/apiwork/representation/inheritance.rb', line 29

def initialize(base_class)
  @base_class = base_class
  @subclasses = []
end

Instance Attribute Details

#base_classClass<Representation::Base> (readonly)

The base class for this inheritance.

Returns:



26
27
28
# File 'lib/apiwork/representation/inheritance.rb', line 26

def base_class
  @base_class
end

#subclassesObject (readonly)



26
27
# File 'lib/apiwork/representation/inheritance.rb', line 26

attr_reader :base_class,
:subclasses

Instance Method Details

#columnSymbol

The column for this inheritance.

Returns:

  • (Symbol)


38
39
40
# File 'lib/apiwork/representation/inheritance.rb', line 38

def column
  @base_class.model_class.inheritance_column.to_sym
end

#mappingHash{String => String}

Mapping of API names to database type values.

Returns:

  • (Hash{String => String})


65
66
67
# File 'lib/apiwork/representation/inheritance.rb', line 65

def mapping
  @subclasses.to_h { |klass| [klass.sti_name, klass.model_class.sti_name] }
end

#register(representation_class) ⇒ Object



69
70
71
# File 'lib/apiwork/representation/inheritance.rb', line 69

def register(representation_class)
  @subclasses << representation_class
end

#resolve(record) ⇒ Class<Representation::Base>?

Resolves a record to its subclass representation.

Parameters:

  • record (ActiveRecord::Base)

    The record to resolve.

Returns:



48
49
50
51
# File 'lib/apiwork/representation/inheritance.rb', line 48

def resolve(record)
  type_value = record.public_send(column)
  @subclasses.find { |klass| klass.model_class.sti_name == type_value }
end

#subclass?(representation_class) ⇒ Boolean

Returns:

  • (Boolean)


73
74
75
# File 'lib/apiwork/representation/inheritance.rb', line 73

def subclass?(representation_class)
  @subclasses.include?(representation_class)
end

#transform?Boolean

Whether this inheritance requires type transformation.

Returns:

  • (Boolean)


57
58
59
# File 'lib/apiwork/representation/inheritance.rb', line 57

def transform?
  @subclasses.any? { |klass| klass.sti_name != klass.model_class.sti_name }
end