Module: NoBrainer::Document::Polymorphic::ClassMethods

Defined in:
lib/no_brainer/document/polymorphic.rb

Instance Method Summary collapse

Instance Method Details

#allObject



47
48
49
50
51
# File 'lib/no_brainer/document/polymorphic.rb', line 47

def all
  criteria = super
  criteria = criteria.where(:_type.in => descendants_type_values) unless is_root_class?
  criteria
end

#descendants_type_valuesObject



35
36
37
# File 'lib/no_brainer/document/polymorphic.rb', line 35

def descendants_type_values
  subclass_tree.map(&:type_value)
end

#inherited(subclass) ⇒ Object



17
18
19
20
21
# File 'lib/no_brainer/document/polymorphic.rb', line 17

def inherited(subclass)
  subclass.is_polymorphic = true
  super
  subclass.field :_type if is_root_class?
end

#is_root_class?Boolean

Returns:



27
28
29
# File 'lib/no_brainer/document/polymorphic.rb', line 27

def is_root_class?
  self == root_class
end

#model_from_attrs(attrs) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/no_brainer/document/polymorphic.rb', line 39

def model_from_attrs(attrs)
  class_name = attrs['_type'] || attrs[:_type]
  return root_class unless class_name
  class_name.to_s.constantize.tap { |cls| raise NameError unless cls <= self }
rescue NameError
  raise NoBrainer::Error::InvalidPolymorphicType, "Invalid polymorphic class: `#{class_name}' is not a `#{self}'"
end

#subclass_treeObject



31
32
33
# File 'lib/no_brainer/document/polymorphic.rb', line 31

def subclass_tree
  [self] + self.descendants
end

#type_valueObject



23
24
25
# File 'lib/no_brainer/document/polymorphic.rb', line 23

def type_value
  name
end