Module: EvenBetterNestedSet

Defined in:
lib/eb_nested_set.rb

Defined Under Namespace

Modules: NestedSet Classes: IllegalAssignmentError, NestedSetError

Instance Method Summary collapse

Instance Method Details

#acts_as_nested_set(options = {}) ⇒ Object

Declare this model as a nested set. Automatically adds all methods in EvenBetterNestedSet::NestedSet to the model, as well as parent and children associations.

Options

left [Symbol]

the name of the column that contains the left boundary [Defaults to left]

right [Symbol]

the name of the column that contains the right boundary [Defaults to right]

scope [Symbol]

the name of an association to scope this nested set to

Parameters:

  • options (Hash) (defaults to: {})

    a set of options



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/eb_nested_set.rb', line 18

def acts_as_nested_set(options={})
  options = { :left => :left, :right => :right }.merge!(options)
  options[:scope] = "#{options[:scope]}_id" if options[:scope]

  include NestedSet

  self.nested_set_options = options

  class_eval "    def \#{options[:left]}=(left)\n      raise EvenBetterNestedSet::IllegalAssignmentError, \"\#{options[:left]} is an internal attribute used by EvenBetterNestedSet, do not assign it directly as is may corrupt the data in your database\"\n    end\n\n    def \#{options[:right]}=(right)\n      raise EvenBetterNestedSet::IllegalAssignmentError, \"\#{options[:right]} is an internal attribute used by EvenBetterNestedSet, do not assign it directly as is may corrupt the data in your database\"\n    end\n  RUBY\n\n  named_scope :roots, :conditions => { :parent_id => nil }, :order => \"\#{nested_set_column(:left)} asc\"\n  has_many :children, :class_name => self.name, :foreign_key => :parent_id, :order => \"\#{nested_set_column(:left)} asc\"\n  belongs_to :parent, :class_name => self.name, :foreign_key => :parent_id\n\n  named_scope :descendants, lambda { |node|\n    left, right = find_boundaries(node.id)\n    { :conditions => [\"\#{nested_set_column(:left)} > ? and \#{nested_set_column(:right)} < ?\", left, right],\n      :order => \"\#{nested_set_column(:left)} asc\" }\n  }\n\n  before_create :append_node\n  before_update :move_node\n  before_destroy :reload\n  after_destroy :remove_node\n  validate_on_update :illegal_nesting\n  validate :validate_parent_is_within_scope\n\n  delegate :nested_set_column, :to => \"self.class\"\nend\n", __FILE__, __LINE__+1