Module: Occams::Extensions::ActsAsTree::ClassMethods

Defined in:
lib/occams/extensions/acts_as_tree.rb

Instance Method Summary collapse

Instance Method Details

#cms_acts_as_tree(options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/occams/extensions/acts_as_tree.rb', line 9

def cms_acts_as_tree(options = {})
  configuration = {
    foreign_key: 'parent_id',
    order: nil,
    counter_cache: nil,
    dependent: :destroy,
    touch: false
  }
  configuration.update(options) if options.is_a?(Hash)

  belongs_to :parent,
             optional: true,
             class_name: name,
             foreign_key: configuration[:foreign_key],
             counter_cache: configuration[:counter_cache],
             touch: configuration[:touch]

  has_many :children,
           -> { order(configuration[:order]) },
           class_name: name,
           foreign_key: configuration[:foreign_key],
           dependent: configuration[:dependent]

  class_eval "    include Occams::Extensions::ActsAsTree::InstanceMethods\n\n    scope :roots, -> {\n      where(\"\#{configuration[:foreign_key]} IS NULL\").\n      order(\#{configuration[:order].nil? ? 'nil' : %(\"\#{configuration[:order]}\")})\n    }\n\n    def self.root\n      roots.first\n    end\n\n    validates_each \"\#{configuration[:foreign_key]}\" do |record, attr, value|\n      if value\n        if record.id == value\n          record.errors.add attr, \"cannot be it's own id\"\n        elsif record.descendants.map {|c| c.id}.include?(value)\n          record.errors.add attr, \"cannot be a descendant's id\"\n        end\n      end\n    end\n  RUBY\nend\n", __FILE__, __LINE__ + 1