Module: TinySupport::ActiveRecord::NestedSet::Model::ClassMethods

Defined in:
lib/tiny_support/active_record/nested_set.rb

Instance Method Summary collapse

Instance Method Details

#all_roots_valid?Boolean

Wrapper for each_root_valid? that can deal with scope.

Returns:

  • (Boolean)


207
208
209
210
211
212
213
214
215
# File 'lib/tiny_support/active_record/nested_set.rb', line 207

def all_roots_valid?
  if acts_as_nested_set_options[:scope]
    roots.group_by {|record| scope_column_names.collect {|col| record.send(col.to_sym) } }.all? do |scope, grouped_roots|
      each_root_valid?(grouped_roots)
    end
  else
    each_root_valid?(roots)
  end
end

#associate_parents(objects) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/tiny_support/active_record/nested_set.rb', line 318

def associate_parents(objects)
  if objects.all?{|o| o.respond_to?(:association)}
    id_indexed = objects.index_by(&:id)
    objects.each do |object|
      if !(association = object.association(:parent)).loaded? && (parent = id_indexed[object.parent_id])
        association.target = parent
        association.set_inverse_instance(parent)
      end
    end
  else
    objects
  end
end

#each_root_valid?(roots_to_validate) ⇒ Boolean

Returns:

  • (Boolean)


217
218
219
220
221
222
223
224
225
# File 'lib/tiny_support/active_record/nested_set.rb', line 217

def each_root_valid?(roots_to_validate)
  left = right = 0
  roots_to_validate.all? do |root|
    (root.left > left && root.right > right).tap do
      left = root.left
      right = root.right
    end
  end
end

#each_with_level(objects) ⇒ Object

Iterates over tree elements and determines the current level in the tree. Only accepts default ordering, odering by an other column than lft does not work. This method is much more efficent than calling level because it doesn’t require any additional database queries.

Example:

Category.each_with_level(Category.root.self_and_descendants) do |o, level|


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/tiny_support/active_record/nested_set.rb', line 272

def each_with_level(objects)
  path = [nil]
  objects.each do |o|
    if o.parent_id != path.last
      # we are on a new level, did we descend or ascend?
      if path.include?(o.parent_id)
        # remove wrong wrong tailing paths elements
        path.pop while path.last != o.parent_id
      else
        path << o.parent_id
      end
    end
    yield(o, path.length - 1)
  end
end

#leavesObject



168
169
170
# File 'lib/tiny_support/active_record/nested_set.rb', line 168

def leaves
  where("#{quoted_right_column_full_name} - #{quoted_left_column_full_name} = 1").order(quoted_left_column_full_name)
end

#left_and_rights_valid?Boolean

Returns:

  • (Boolean)


176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/tiny_support/active_record/nested_set.rb', line 176

def left_and_rights_valid?
  ## AS clause not supported in Oracle in FROM clause for aliasing table name
  joins("LEFT OUTER JOIN #{quoted_table_name}" +
        (connection.adapter_name.match(/Oracle/).nil? ?  " AS " : " ") +
        "parent ON " +
        "#{quoted_parent_column_full_name} = parent.#{primary_key}").
  where(
    "#{quoted_left_column_full_name} IS NULL OR " +
    "#{quoted_right_column_full_name} IS NULL OR " +
    "#{quoted_left_column_full_name} >= " +
    "#{quoted_right_column_full_name} OR " +
    "(#{quoted_parent_column_full_name} IS NOT NULL AND " +
    "(#{quoted_left_column_full_name} <= parent.#{quoted_left_column_name} OR " +
    "#{quoted_right_column_full_name} >= parent.#{quoted_right_column_name}))"
        ).count == 0
end

#nested_set_options(options = {}, &block) ⇒ Object

Returns options for select. You can exclude some items from the tree. You can pass a block receiving an item and returning the string displayed in the select.

Params

* +class_or_item+ - Class name or top level times
* +mover+ - The item that is being move, used to exlude impossible moves
* +&block+ - a block that will be used to display: { |item| ... item.name }

Usage

<%= f.select :parent_id, Category.nested_set_options(:item => item, :mover => @category) {|i|
    "#{'–' * i.level} #{i.name}"
  }) %>


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
# File 'lib/tiny_support/active_record/nested_set.rb', line 131

def nested_set_options options={}, &block
  mover = options[:mover]

  _items = options[:items] || options[:item]

  if _items.is_a?(Array)
    items = _items.reject { |e| !e.root? }
  elsif _items.is_a?(self)
    items = Array(_items)
  else
    items = self.roots
  end

  result = []
  items.each do |root|
    result += root.class.associate_parents(root.self_and_descendants).map do |i|
      if mover.nil? || mover.new_record? || mover.move_possible?(i)
        if block_given?
          [block.call(i), i.id]
        else
          [i.name_with_level, i.id]
        end
      end
    end.compact
  end
  result
end

#no_duplicates_for_columns?Boolean

Returns:

  • (Boolean)


193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/tiny_support/active_record/nested_set.rb', line 193

def no_duplicates_for_columns?
  scope_string = Array(acts_as_nested_set_options[:scope]).map do |c|
    connection.quote_column_name(c)
  end.push(nil).join(", ")
  [quoted_left_column_full_name, quoted_right_column_full_name].all? do |column|
    # No duplicates
    select("#{scope_string}#{column}, COUNT(#{column})").
      group("#{scope_string}#{column}").
      having("COUNT(#{column}) > 1").
      first.nil?
  end
end

#rebuild!(validate_nodes = true) ⇒ Object

Rebuilds the left & rights if unset or invalid. Also very useful for converting from acts_as_tree.



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/tiny_support/active_record/nested_set.rb', line 229

def rebuild!(validate_nodes = true)
  # default_scope with order may break database queries so we do all operation without scope
  unscoped do
    # Don't rebuild a valid tree.
    return true if valid?

    scope = lambda{|node|}
    if acts_as_nested_set_options[:scope]
      scope = lambda{|node|
        scope_column_names.inject(""){|str, column_name|
          str << "AND #{connection.quote_column_name(column_name)} = #{connection.quote(node.send(column_name.to_sym))} "
        }
      }
    end
    indices = {}

    set_left_and_rights = lambda do |node|
      # set left
      node[left_column_name] = indices[scope.call(node)] += 1
      # find
      where(["#{quoted_parent_column_full_name} = ? #{scope.call(node)}", node]).order("#{quoted_left_column_full_name}, #{quoted_right_column_full_name}, id").each{|n| set_left_and_rights.call(n) }
      # set right
      node[right_column_name] = indices[scope.call(node)] += 1
      node.save!(:validate => validate_nodes)
    end

    # Find root node(s)
    self.where("#{quoted_parent_column_full_name} IS NULL").order("#{quoted_left_column_full_name}, #{quoted_right_column_full_name}, id").each do |root_node|
      # setup index for this scope
      indices[scope.call(root_node)] ||= 0
      set_left_and_rights.call(root_node)
    end
  end
end

#rootObject

Returns the first root



160
161
162
# File 'lib/tiny_support/active_record/nested_set.rb', line 160

def root
  roots.first
end

#rootsObject



164
165
166
# File 'lib/tiny_support/active_record/nested_set.rb', line 164

def roots
  where(parent_column_name => nil).order(quoted_left_column_full_name)
end

#sorted_each_with_level(objects, order) ⇒ Object

Same as each_with_level - Accepts a string as a second argument to sort the list Example:

Category.each_with_level(Category.root.self_and_descendants, :sort_by_this_column) do |o, level|


291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/tiny_support/active_record/nested_set.rb', line 291

def sorted_each_with_level(objects, order)
  path = [nil]
  children = []
  objects.each do |o|
    children << o if o.leaf?
    if o.parent_id != path.last
      if !children.empty? && !o.leaf?
        children.sort_by! &order
        children.each { |c| yield(c, path.length-1) }
        children = []
      end
      # we are on a new level, did we decent or ascent?
      if path.include?(o.parent_id)
        # remove wrong wrong tailing paths elements
        path.pop while path.last != o.parent_id
      else
        path << o.parent_id
      end
    end
    yield(o,path.length-1) if !o.leaf?
  end
  if !children.empty?
    children.sort_by! &order
    children.each { |c| yield(c, path.length-1) }
  end
end

#valid?Boolean

Returns:

  • (Boolean)


172
173
174
# File 'lib/tiny_support/active_record/nested_set.rb', line 172

def valid?
  left_and_rights_valid? && no_duplicates_for_columns? && all_roots_valid?
end