f8a83c4b86fa8c9e37f0a010c96782660ffd43fe
[redakcja_redmine.git] / lib / redmine_publications / issue_patch.rb
1 module RedminePublications
2   # Patches Redmine's Issues dynamically. Adds a +after_save+ filter.
3
4   module IssuePatch
5     def self.included(base) # :nodoc:
6       base.extend(ClassMethods)
7  
8       base.send(:include, InstanceMethods)
9  
10       # Same as typing in the class
11       base.class_eval do
12         unloadable # Send unloadable so it will not be unloaded in development
13  
14         validate :check_relations
15         after_save :update_relations
16  
17         # Add visible to Redmine 0.8.x
18         unless respond_to?(:visible)
19           named_scope :visible, lambda {|*args| { :include => :project,
20               :conditions => Project.allowed_to_condition(args.first || User.current, :view_issues) } }
21         end
22       end
23  
24     end
25     
26     module ClassMethods
27     end
28     
29     module InstanceMethods
30
31       def publication_names     
32         if not @pubnames
33           self.publications.map { |pub| pub.name }
34         else
35           @pubnames        
36         end
37       end
38
39       def publication_names=(value)
40         @pubnames = value.sort!
41       end
42
43       def publications
44         Publication.all( 
45           :joins => 
46             "JOIN issue_publications ON (issue_publications.publication_id = publications.id)",
47           :conditions =>
48             ["issue_publications.issue_id = ? ", self.id] )     
49       end
50
51       def check_relations
52         current_names = self.publication_names
53         non_existant = []
54
55         pubs =  Publication.find_all_by_name(current_names).map {|i| i.name}
56         missing = current_names.select {|name| not pubs.include?name }
57
58         if not missing.empty?
59           errors.add("publications", "Missing publication(s): " + missing.join(', '))
60         end
61      end
62
63      def update_relations
64         self.reload
65         old = self.publications
66         current_names = self.publication_names
67
68         # delete unused relations
69         deleted = old.select { |v| not (current_names.include?(v.name)) }
70         deleted.each do |pub| 
71           IssuePublication.delete_all(["issue_publications.issue_id = ? AND issue_publications.publication_id = ?", self.id, pub.id])
72         end
73
74         current_names.each do |name|    
75             pub = Publication.find_by_name(name)
76             IssuePublication.find_or_create_by_publication_id_and_issue_id(pub.id, self.id)
77         end
78
79         return true
80      end
81
82     end
83   end
84 end