dbcbfa8fc01112bc9a837fac9ff64d3b16ea24c1
[redakcja.git] / redmine / redmine_publications / 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         after_save :update_relations
15         # after_destroy :check_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       def source_files
31         if not @source_files
32           @source_files = self.lookup_source_files.map { |pub| pub.source_file }
33         end
34         @source_files        
35       end
36
37       def source_files=(value)
38         @source_files = value
39       end
40
41       def lookup_source_files
42         Publication.all( 
43           :joins => 
44             "JOIN issue_publications ON (issue_publications.publication_id = publications.id)",
45           :conditions =>
46             [" issue_publications.issue_id = ? ", self.id] )    
47       end
48         
49       def update_relations
50         self.reload
51         current_assocs = self.lookup_source_files
52         new_assocs_names = self.source_files.split(' ')
53
54         # delete unused relations
55         deleted = current_assocs.select { |v| not (new_assocs_names.include?(v.source_file)) }
56         deleted.each { |pub| IssuePublication.delete_all( 
57           :contitions => ["issue_publications.issue_id = ? AND issue_publicatons.publication_id = ?",
58                 self.id, pub.id]) }
59
60         new_assocs_names.each do |name|
61                 pub = Publication.find_or_create_by_source_file(name)
62                 IssuePublication.find_or_create_by_publication_id_and_issue_id(pub.id, self.id)
63         end
64
65         return true
66       end
67
68     end
69   end
70 end