Module: Caracal::Core::Relationships

Included in:
Document
Defined in:
lib/caracal/core/relationships.rb

Overview

This module encapsulates all the functionality related to registering and retrieving relationships.

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/caracal/core/relationships.rb', line 12

def self.included(base)
  base.class_eval do
    
    #-------------------------------------------------------------
    # Configuration
    #-------------------------------------------------------------
    
    attr_reader :relationship_counter
    
    
    #-------------------------------------------------------------
    # Class Methods
    #-------------------------------------------------------------
    
    def self.default_relationships
      [
        { target: 'fontTable.xml',  type: :font      },
        { target: 'footer1.xml',    type: :footer    },
        { target: 'numbering.xml',  type: :numbering },
        { target: 'settings.xml',   type: :setting   },
        { target: 'styles.xml',     type: :style     }
      ]           
    end
    
    
    #-------------------------------------------------------------
    # Public Methods
    #-------------------------------------------------------------
    
    #============== ATTRIBUTES ==========================
    
    def relationship(options={}, &block)
      id = relationship_counter.to_i + 1
      options.merge!({ id: id })

      model = Caracal::Core::Models::RelationshipModel.new(options, &block)
      if model.valid?
        @relationship_counter = id
        rel = register_relationship(model)
      else
        raise Caracal::Errors::InvalidModelError, 'relationship must specify the :id, :target, and :type attributes.'
      end
      rel
    end
    
    
    #============== GETTERS =============================
    
    def relationships
      @relationships ||= []
    end
              
    def find_relationship(target)
      relationships.find { |r| r.matches?(target) }
    end
    
    
    #============== REGISTRATION ========================
    
    def register_relationship(model)
      unless r = find_relationship(model.relationship_target)
        relationships << model
        r = model
      end
      r
    end
    
    def unregister_relationship(target)
      if r = find_relationship(target)
        relationships.delete(r)
      end
    end
    
  end
end