Rails ActiveRecord中的私有new和create方法?

时间:2015-07-07 22:58:43

标签: ruby-on-rails ruby activerecord constructor private

我有一个ActiveRecord,它是一个n-ary树的节点。模型中有许多类方法可以创建根,附加叶子等等......

当每个插入修改整个树时,我想避免外部类通过new和create方法实例化我的模型。

知道怎么做吗? (我在Rails 4.0.2中)

更新

因此,我使用的树结构的表示是一种非递归表示 - 按间隔。 The implementation is described there,但它是法语。

基本上,每个节点都有一个表示间隔的left_tree和right_tree。节点子节点的left_tree和right_tree位于父节点的间隔内。这种表示允许我在树上进行非常快速的选择,但另一方面有大量的插入程序。

# Task schema
create_table "tasks", force: true do |t|
   t.string   "label"
   t.integer  "tree_level"
   t.integer  "left_tree"
   t.integer  "right_tree"
end

然后,为了插入,我需要所有树的间隔索引。

# Model Task

# Create the root of the tree. Only static method of the model
def self.create_root! label
  Task.create! do |task|
      task.tree_level = 1
      task.left_tree = 1
      task.right_tree = 2
      task.label = label
  end
end

# Method to add a child for a node. Task model
def create_child! label
  new_task = Task.new

  Task.transaction do
    # Prepare the new task to be inserted in the intervals
    new_task.left_tree = right_tree
    new_task.right_tree = right_tree + 1
    new_task.tree_level = tree_level + 1
    new_task.label = label

    # create an empty space in the tree
    Task.where(
      'right_tree >= :right_tree', 
      { right_tree: right_tree }).update_all('right_tree = right_tree + 2')
    Task.where(
      'left_tree >= :right_tree', 
      { right_tree: right_tree }).update_all('left_tree = left_tree + 2')

    # Save the task, which have now a place in the tree.
    new_task.save!
  end

  reload
  return new_task
end

正如您所看到的,模型永远不应该在我的模型Task之外实例化。 我们应该创建一个根,然后从这个根创建整个树,方法是create_child!

1 个答案:

答案 0 :(得分:1)

您可以选择更改界面:

# Just makin a sample base class.
# In your case it would be ActiveRecord::Base
class RecordBase
  def self.create(label)
    record = new
    record.label = label
    record.save
    record
  end

  def save
    true
  end
end

class Task < RecordBase
  # Make the given class methods private.
  private_class_method :new, :create

  # Creates and returns the root.
  def self.create_root(label)
    # Task.create won't work here since create is private.
    create(label)
  end

  def self.create_child(parent, label)
    # Task.new won't work here since new is private.
    child = new
    child.label = label
    # other stuffs like :
    # child.attr = parent.attr
    child.save
    child
  end

  def create_child(label)
    self.class.create_child(self, label)
  end
end

# Things that don't work :
# task = Task.new
# task = Task.create('label')

# Working part :
# Creates and gets the root.
root = Task.create_root('label')

# Creates a child
child = root.create_child('label')

用户可以拨打Task.create_child(parent, label),但我认为这不会有问题,因为它使用与task.create_child(label)相同的算法。