Module: Traits::Model::Inheritance

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

Instance Method Summary collapse

Instance Method Details

#inheritance_attributeObject



21
22
23
# File 'lib/traits/model/inheritance.rb', line 21

def inheritance_attribute
  attributes[active_record.inheritance_column]
end

#inheritance_attribute_nameObject



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

def inheritance_attribute_name
  inheritance_attribute.name if uses_inheritance?
end

#inheritance_baseObject



56
57
58
# File 'lib/traits/model/inheritance.rb', line 56

def inheritance_base
  inheritance_chain[0]
end

#inheritance_base?Boolean

Returns:

  • (Boolean)


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

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

#inheritance_chainObject

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]



45
46
47
48
49
50
51
52
53
54
# File 'lib/traits/model/inheritance.rb', line 45

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

#inheritance_derived?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/traits/model/inheritance.rb', line 17

def inheritance_derived?
  !active_record.descends_from_active_record?
end

#to_hashObject



60
61
62
63
64
65
66
67
# File 'lib/traits/model/inheritance.rb', line 60

def to_hash
  super.merge!(
    is_inheritance_base:        inheritance_base?,
    is_inheritance_derived:     inheritance_derived?,
    inheritance_attribute_name: inheritance_attribute.try(:name),
    inheritance_chain:          inheritance_chain.map { |active_record| active_record.traits.name }
  )
end

#uses_inheritance?Boolean

Returns:

  • (Boolean)


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

def uses_inheritance?
  inheritance_base? || inheritance_derived?
end