Module: Ancestry::ClassMethods

Defined in:
lib/ancestry/class_methods.rb

Constant Summary collapse

ANCESTRY_UNCAST_TYPES =
[:string, :uuid, :text].freeze

Instance Method Summary collapse

Instance Method Details

#arrange(options = {}) ⇒ Object

Get all nodes and sort them into an empty hash



32
33
34
35
36
37
38
# File 'lib/ancestry/class_methods.rb', line 32

def arrange(options = {})
  if (order = options.delete(:order))
    arrange_nodes(ancestry_base_class.order(order).where(options))
  else
    arrange_nodes(ancestry_base_class.where(options))
  end
end

#arrange_nodes(nodes, orphan_strategy: :rootify) ⇒ Object

arranges array of nodes to a hierarchical hash

If a node’s parent is not included, the node will be included as if it is a top level node

Parameters:

  • nodes to be arranged

  • (defaults to: :rootify)

    :rootify or :destroy (default: :rootify)



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/ancestry/class_methods.rb', line 46

def arrange_nodes(nodes, orphan_strategy: :rootify)
  node_ids = Set.new(nodes.map(&:id))
  index = Hash.new { |h, k| h[k] = {} }

  nodes.each_with_object({}) do |node, arranged|
    index[node.parent_id][node] = children = index[node.id]
    if node.parent_id.nil?
      arranged[node] = children
    elsif !node_ids.include?(node.parent_id)
      case orphan_strategy
      when :destroy
         # All children are destroyed as well (default)
      when :adopt
        raise ArgumentError, "Not Implemented"
      when :rootify
        arranged[node] = children
      when :restrict
        raise Ancestry::AncestryException, I18n.t("ancestry.cannot_delete_descendants")
      end
    end
  end
end

#arrange_serializable(options = {}, nodes = nil, &block) ⇒ Object

Arrangement to nested array for serialization You can also supply your own serialization logic using blocks also allows you to pass the order just as you can pass it to the arrange method



84
85
86
87
88
89
90
91
92
93
# File 'lib/ancestry/class_methods.rb', line 84

def arrange_serializable(options = {}, nodes = nil, &block)
  nodes = arrange(options) if nodes.nil?
  nodes.map do |parent, children|
    if block_given?
      yield parent, arrange_serializable(options, children, &block)
    else
      parent.serializable_hash.merge 'children' => arrange_serializable(options, children)
    end
  end
end

#build_ancestry_from_parent_ids!(column = :parent_id, parent_id = nil, ancestor_ids = []) ⇒ Object

Build ancestry from parent ids for migration purposes



214
215
216
217
218
219
220
221
222
223
# File 'lib/ancestry/class_methods.rb', line 214

def build_ancestry_from_parent_ids!(column = :parent_id, parent_id = nil, ancestor_ids = [])
  unscoped_where do |scope|
    scope.where(column => parent_id).find_each do |node|
      node.without_ancestry_callbacks do
        node.update_attribute :ancestor_ids, ancestor_ids
      end
      build_ancestry_from_parent_ids! column, node.id, ancestor_ids + [node.id]
    end
  end
end

#check_ancestry_integrity!(options = {}) ⇒ Object

Integrity checking compromised tree integrity is unlikely without explicitly setting cyclic parents or invalid ancestry and circumventing validation just in case, raise an AncestryIntegrityException if issues are detected specify :report => :list to return an array of exceptions or :report => :echo to echo any error messages



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/ancestry/class_methods.rb', line 131

def check_ancestry_integrity!(options = {})
  parents = {}
  exceptions = [] if options[:report] == :list

  unscoped_where do |scope|
    # For each node ...
    scope.find_each do |node|
      # ... check validity of ancestry column
      if !node.sane_ancestor_ids?
        raise Ancestry::AncestryIntegrityException, I18n.t("ancestry.invalid_ancestry_column",
                                                           :node_id => node.id,
                                                           :ancestry_column => node.read_attribute(node.class.ancestry_column))
      end
      # ... check that all ancestors exist
      node.ancestor_ids.each do |ancestor_id|
        unless exists?(ancestor_id)
          raise Ancestry::AncestryIntegrityException, I18n.t("ancestry.reference_nonexistent_node",
                                                             :node_id => node.id,
                                                             :ancestor_id => ancestor_id)
        end
      end
      # ... check that all node parents are consistent with values observed earlier
      node.path_ids.zip([nil] + node.path_ids).each do |node_id, parent_id|
        parents[node_id] = parent_id unless parents.key?(node_id)
        unless parents[node_id] == parent_id
          raise Ancestry::AncestryIntegrityException, I18n.t("ancestry.conflicting_parent_id",
                                                             :node_id => node_id,
                                                             :parent_id => parent_id || 'nil',
                                                             :expected => parents[node_id] || 'nil')
        end
      end
    rescue Ancestry::AncestryIntegrityException => e
      case options[:report]
      when :list then exceptions << e
      when :echo then puts e
      else raise e
      end
    end
  end
  exceptions if options[:report] == :list
end

#flatten_arranged_nodes(arranged, nodes = []) ⇒ Object

convert a hash of the form => children to an array of nodes, child first

Parameters:

  • arranged nodes



73
74
75
76
77
78
79
# File 'lib/ancestry/class_methods.rb', line 73

def flatten_arranged_nodes(arranged, nodes = [])
  arranged.each do |node, children|
    nodes << node
    flatten_arranged_nodes(children, nodes) unless children.empty?
  end
  nodes
end

#primary_key_is_an_integer?Boolean

Returns:



272
273
274
275
276
277
278
# File 'lib/ancestry/class_methods.rb', line 272

def primary_key_is_an_integer?
  if defined?(@primary_key_is_an_integer)
    @primary_key_is_an_integer
  else
    @primary_key_is_an_integer = !ANCESTRY_UNCAST_TYPES.include?(type_for_attribute(primary_key).type)
  end
end

#rebuild_counter_cache!Object



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/ancestry/class_methods.rb', line 244

def rebuild_counter_cache!
  if %w(mysql mysql2).include?(connection.adapter_name.downcase)
    connection.execute %{
      UPDATE #{table_name} AS dest
      LEFT JOIN (
        SELECT #{table_name}.#{primary_key}, COUNT(*) AS child_count
        FROM #{table_name}
        JOIN #{table_name} children ON children.#{ancestry_column} = (#{child_ancestry_sql})
        GROUP BY #{table_name}.#{primary_key}
      ) src USING(#{primary_key})
      SET dest.#{counter_cache_column} = COALESCE(src.child_count, 0)
    }
  else
    update_all %{
      #{counter_cache_column} = (
        SELECT COUNT(*)
        FROM #{table_name} children
        WHERE children.#{ancestry_column} = (#{child_ancestry_sql})
      )
    }
  end
end

#rebuild_depth_cache!Object

Rebuild depth cache if it got corrupted or if depth caching was just turned on

Raises:



226
227
228
229
230
231
232
233
234
235
236
# File 'lib/ancestry/class_methods.rb', line 226

def rebuild_depth_cache!
  raise(Ancestry::AncestryException, I18n.t("ancestry.cannot_rebuild_depth_cache")) unless respond_to?(:depth_cache_column)

  ancestry_base_class.transaction do
    unscoped_where do |scope|
      scope.find_each do |node|
        node.update_attribute depth_cache_column, node.depth
      end
    end
  end
end

#rebuild_depth_cache_sql!Object

NOTE: this is temporarily kept separate from rebuild_depth_cache! this will become the implementation of rebuild_depth_cache!



240
241
242
# File 'lib/ancestry/class_methods.rb', line 240

def rebuild_depth_cache_sql!
  update_all("#{depth_cache_column} = #{ancestry_depth_sql}")
end

#restore_ancestry_integrity!Object

Integrity restoration



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/ancestry/class_methods.rb', line 174

def restore_ancestry_integrity!
  parent_ids = {}
  # Wrap the whole thing in a transaction ...
  ancestry_base_class.transaction do
    unscoped_where do |scope|
      # For each node ...
      scope.find_each do |node|
        # ... set its ancestry to nil if invalid
        if !node.sane_ancestor_ids?
          node.without_ancestry_callbacks do
            node.update_attribute :ancestor_ids, []
          end
        end
        # ... save parent id of this node in parent_ids array if it exists
        parent_ids[node.id] = node.parent_id if exists? node.parent_id

        # Reset parent id in array to nil if it introduces a cycle
        parent_id = parent_ids[node.id]
        until parent_id.nil? || parent_id == node.id
          parent_id = parent_ids[parent_id]
        end
        parent_ids[node.id] = nil if parent_id == node.id
      end

      # For each node ...
      scope.find_each do |node|
        # ... rebuild ancestry from parent_ids array
        ancestor_ids, parent_id = [], parent_ids[node.id]
        until parent_id.nil?
          ancestor_ids, parent_id = [parent_id] + ancestor_ids, parent_ids[parent_id]
        end
        node.without_ancestry_callbacks do
          node.update_attribute :ancestor_ids, ancestor_ids
        end
      end
    end
  end
end

#scope_depth(depth_options, depth) ⇒ Object

Scope on relative depth options



15
16
17
18
19
20
21
22
23
24
# File 'lib/ancestry/class_methods.rb', line 15

def scope_depth(depth_options, depth)
  depth_options.inject(ancestry_base_class) do |scope, option|
    scope_name, relative_depth = option
    if [:before_depth, :to_depth, :at_depth, :from_depth, :after_depth].include? scope_name
      scope.send scope_name, depth + relative_depth
    else
      raise Ancestry::AncestryException, I18n.t("ancestry.unknown_depth_option", scope_name: scope_name)
    end
  end
end

#sort_by_ancestry(nodes) ⇒ Object

Pseudo-preordered array of nodes. Children will always follow parents, This is deterministic unless the parents are missing and a sort block is specified



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/ancestry/class_methods.rb', line 111

def sort_by_ancestry(nodes)
  arranged = nodes if nodes.is_a?(Hash)

  unless arranged
    presorted_nodes = nodes.sort do |a, b|
      rank = (a.public_send(ancestry_column) || ' ') <=> (b.public_send(ancestry_column) || ' ')
      rank = yield(a, b) if rank == 0 && block_given?
      rank
    end

    arranged = arrange_nodes(presorted_nodes)
  end

  flatten_arranged_nodes(arranged)
end

#to_node(object) ⇒ Object

Fetch tree node if necessary



6
7
8
9
10
11
12
# File 'lib/ancestry/class_methods.rb', line 6

def to_node(object)
  if object.is_a?(ancestry_base_class)
    object
  else
    unscoped_where { |scope| scope.find(object.try(primary_key) || object) }
  end
end

#tree_view(column, data = nil) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/ancestry/class_methods.rb', line 95

def tree_view(column, data = nil)
  data ||= arrange
  data.each do |parent, children|
    if parent.depth == 0
      puts parent[column]
    else
      num = parent.depth - 1
      indent = "   " * num
      puts " #{"|" if parent.depth > 1}#{indent}|_ #{parent[column]}"
    end
    tree_view(column, children) if children
  end
end

#unscoped_where {|ancestry_base_class.default_scoped.unscope(:where)| ... } ⇒ Object

Yields:

  • (ancestry_base_class.default_scoped.unscope(:where))


267
268
269
# File 'lib/ancestry/class_methods.rb', line 267

def unscoped_where
  yield ancestry_base_class.default_scoped.unscope(:where)
end