Module: Traits::Model::Inheritance

Included in:
Traits::Model
Defined in:
lib/traits/model/inheritance.rb

Instance Method Summary collapse

Instance Method Details

#inheritance_attributeObject Also known as: sti_attribute



24
25
26
# File 'lib/traits/model/inheritance.rb', line 24

def inheritance_attribute
  attributes[model_class.inheritance_column]
end

#inheritance_attribute_nameObject Also known as: sti_attribute_name



29
30
31
# File 'lib/traits/model/inheritance.rb', line 29

def inheritance_attribute_name
  inheritance_attribute.name if uses_inheritance?
end

#inheritance_baseObject



62
63
64
# File 'lib/traits/model/inheritance.rb', line 62

def inheritance_base
  inheritance_chain[0]
end

#inheritance_base?Boolean Also known as: sti_base?

Returns:

  • (Boolean)


12
13
14
15
16
# File 'lib/traits/model/inheritance.rb', line 12

def inheritance_base?
  model_class.descends_from_active_record? &&
    !model_class.abstract_class? &&
    model_class.subclasses.any? { |subclass| subclass.superclass == model_class }
end

#inheritance_chainObject Also known as: sti_chain

class File < ActiveRecord::Base end

class Photo < File end

class Video < File end

class Portrait < Photo end

File.traits.inheritance_chain => [File] Photo.traits.inheritance_chain => [File, Photo] Video.traits.inheritance_chain => [File, Video] Portrait.traits.inheritance_chain => [File, Photo, Portrait]



50
51
52
53
54
55
56
57
58
59
# File 'lib/traits/model/inheritance.rb', line 50

def inheritance_chain
  Traits.load_active_record_descendants!
  model_class = self.model_class
  chain       = [model_class]
  until model_class.superclass == ActiveRecord::Base do
    model_class = model_class.superclass
    chain.unshift(model_class)
  end
  chain
end

#inheritance_derived?Boolean Also known as: sti_derived?

Returns:

  • (Boolean)


19
20
21
# File 'lib/traits/model/inheritance.rb', line 19

def inheritance_derived?
  !model_class.descends_from_active_record?
end

#to_hashObject



66
67
68
69
70
71
72
73
# File 'lib/traits/model/inheritance.rb', line 66

def to_hash
  super.merge!(
    is_sti_base:        sti_base?,
    is_sti_derived:     sti_derived?,
    sti_attribute_name: sti_attribute_name,
    sti_chain:          sti_chain.map { |model_class| model_class.traits.name }
  )
end

#uses_inheritance?Boolean Also known as: uses_sti?

Returns:

  • (Boolean)


7
8
9
# File 'lib/traits/model/inheritance.rb', line 7

def uses_inheritance?
  inheritance_base? || inheritance_derived?
end