Module: Hierarchable

Extended by:
ActiveSupport::Concern
Defined in:
lib/hierarchable/hierarchable.rb,
lib/hierarchable/version.rb

Overview

All objects that want to make use of this concern must have three columns defined:

hierarchy_root: The root node in the hierarchy hierarchy (polymorphic)
hierarchy_parent: The parent of the current object (polymorphic)
hierarchy_ancestors_path: The string representation of all ancestors of
                          the current object (string).

The ‘hierarchy_ancestors_path` column does contain all of the information that is in the `hierarchy_root` and `hierarchy_parent` columns, but those two columns are created for more efficient querying as the direct parent and the root are the most frequent parts of the hierarchy that are needed.

To set the attribute that should be used as the parent, one needs to set the ‘parent_source` value when including this in a model.

class A
  include Hierarchable
  hierarchable parent_source: :some_column
end

If some model doesn’t have a parent (e.g. it’s the root of the hierarchy) then the ‘parent_source` can be ommited or explicitly set to `nil`

class B
  include Hierarchable
  hierarchable parent_source: nil
end

class AlternateB
  include Hierarchable
  hierarchable
end

There are times when the parent is dependent on the state of an object. For example, let’s assume that a Project can have tasks, and that tasks can also have tasks (sub tasks). Assuming that the Task model has both ‘project` and `parent_task` attributes, we could define the parent source dynamically as follows:

class Task
  include Hierarchable
  hierarchable parent_source: ->(obj) {
    obj.parent_task.present ? :parent_task : :project
  }
end

By default the separators to use for the path and records are / and | respectively. This means that a hierarchy path will look something like

<record1_type>|<record1_id>/<record2_type>|<record2_id>

A user can change this default behavior by setting the ‘path_separator` and/or `record_seprator` option when including this in a class. For example:

class Foo
  include Hierarchable
  hierachable path_separator: '##', record_separator: '@@'
end

CAUTION: When setting custom path and/or record separators, do not use any characters that are likely to be in class/module names such as -, _, :, etc.

Defined Under Namespace

Modules: InstanceMethods

Constant Summary collapse

VERSION =
'0.4.0'
HIERARCHABLE_DEFAULT_PATH_SEPARATOR =
'/'
HIERARCHABLE_DEFAULT_RECORD_SEPARATOR =
'|'

Instance Method Summary collapse

Instance Method Details

#class_for_association(association) ⇒ Object

Get the class that is associated with a given association



704
705
706
707
708
# File 'lib/hierarchable/hierarchable.rb', line 704

def class_for_association(association)
  self.association(association)
      .reflection
      .klass
end