Module: Julik::MakeLikeTree::ClassMethods

Defined in:
lib/make_like_a_tree.rb

Instance Method Summary collapse

Instance Method Details

#make_like_a_tree(options = {}) ⇒ Object

An acts_as_threaded on steroids. Configuration options are:

  • root_column - specifies the column name to use for identifying the root thread, default “root_id”

  • parent_column - specifies the column name to use for keeping the position integer, default “parent_id”

  • left_column - column name for left boundary data, default “lft”

  • right_column - column name for right boundary data, default “rgt”

  • depth - column name used to track the depth in the branch, default “depth”

  • scope - adds an additional contraint on the threads when searching or updating



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
55
56
57
58
59
60
61
62
63
64
# File 'lib/make_like_a_tree.rb', line 26

def make_like_a_tree(options = {})
  configuration = { :root_column => "root_id", :parent_column => "parent_id", :left_column => "lft", :right_column => "rgt", :depth_column => 'depth', :scope => "(1=1)" }
  configuration.update(options) if options.is_a?(Hash)
  configuration[:scope] = "#{configuration[:scope]}_id".intern if configuration[:scope].is_a?(Symbol) && configuration[:scope].to_s !~ /_id$/

  if configuration[:scope].is_a?(Symbol)
    scope_condition_method = %(
      def scope_condition
        if #{configuration[:scope].to_s}.nil?
          "#{configuration[:scope].to_s} IS NULL"
        else
          "#{configuration[:scope].to_s} = \#{#{configuration[:scope].to_s}}"
        end
      end
    )
  else
    scope_condition_method = "def scope_condition() \"#{configuration[:scope]}\" end"
  end
  
  after_create :apply_parenting_after_create
  
  
 # before_update :register_parent_id_before_update, :unless => :new_record?
#  after_update :replant_after_update
  
  # TODO: refactor for class << self
  class_eval <<-EOV
    include Julik::MakeLikeTree::InstanceMethods

    #{scope_condition_method}

    def root_column() "#{configuration[:root_column]}" end
    def parent_column() "#{configuration[:parent_column]}" end
    def left_col_name() "#{configuration[:left_column]}" end
    def right_col_name() "#{configuration[:right_column]}" end
    def depth_column() "#{configuration[:depth_column]}" end

  EOV
end