Module: Spider::Model::Tree

Defined in:
lib/spiderfw/model/mixins/tree.rb

Defined Under Namespace

Modules: ClassMethods, MapperMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(model) ⇒ Object



5
6
7
8
# File 'lib/spiderfw/model/mixins/tree.rb', line 5

def self.included(model)
    model.extend(ClassMethods)
    model.mapper_include(MapperMethods)
end

Instance Method Details

#before_saveObject



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/spiderfw/model/mixins/tree.rb', line 50

def before_save
    self.class.elements_array.select{ |el| el.attributes[:association] == :tree }.each do |el|
        if element_modified?(el)
            cnt = 1
            self.get(el).each do |obj|
                obj.set(el.attributes[:tree_position], cnt)
                cnt += 1
            end
        end
    end
    super
end

#tree_all(element) ⇒ Object



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
# File 'lib/spiderfw/model/mixins/tree.rb', line 10

def tree_all(element)
    element = self.class.elements[element] unless element.is_a?(Element)
    left_el = element.attributes[:tree_left]
    right_el = element.attributes[:tree_right]
    left = get(left_el)
    right = get(right_el)
    return nil unless (left && right)
    c = Condition.and
    c[left_el] = (left..right)
    q = Query.new(c)
    q.order_by(left_el) unless element.attributes[:order] == false
    res = element.model.find(q)
    return [] unless res
    right_stack = []
    parents = []
    first = nil
    res.each do |obj|
        first ||= obj
        if right_stack.length > 0
            while right_stack.length > 0 && right_stack.last < obj.get(right_el)
                right_stack.pop
                p, sub = parents.pop
                p.set_loaded_value(element.name, sub)
                parents.last[1] << p if parents.last
            end
            obj.set(element.attributes[:tree_depth], right_stack.length)
        end
        right_stack << obj.get(right_el)
        parents << [obj, QuerySet.static(self.class)]
    end
    
    while pair = parents.pop
        p, sub = pair
        p.set_loaded_value(element.name, sub)
        parents.last[1] << p if parents.last
    end
    
    return res
end