]> git.openstreetmap.org Git - rails.git/blob - app/models/note.rb
Merge branch 'notes'
[rails.git] / app / models / note.rb
1 class Note < ActiveRecord::Base
2   include GeoRecord
3
4   has_many :comments, :class_name => "NoteComment",
5                       :foreign_key => :note_id,
6                       :order => :created_at,
7                       :conditions => { :visible => true }
8
9   validates_presence_of :id, :on => :update
10   validates_uniqueness_of :id
11   validates_numericality_of :latitude, :only_integer => true
12   validates_numericality_of :longitude, :only_integer => true
13   validates_presence_of :closed_at if :status == "closed"
14   validates_inclusion_of :status, :in => ["open", "closed", "hidden"]
15   validate :validate_position
16
17   attr_accessible :lat, :lon
18
19   after_initialize :set_defaults
20
21   # Sanity check the latitude and longitude and add an error if it's broken
22   def validate_position
23     errors.add(:base, "Note is not in the world") unless in_world?
24   end
25
26   # Close a note
27   def close
28     self.status = "closed"
29     self.closed_at = Time.now.getutc
30     self.save
31   end
32
33   # Return a flattened version of the comments for a note
34   def flatten_comment(separator_char, upto_timestamp = :nil)
35     resp = ""
36     comment_no = 1
37     self.comments.each do |comment|
38       next if upto_timestamp != :nil and comment.created_at > upto_timestamp
39       resp += (comment_no == 1 ? "" : separator_char)
40       resp += comment.body if comment.body
41       resp += " [ " 
42       resp += comment.author.display_name if comment.author
43       resp += " " + comment.created_at.to_s + " ]"
44       comment_no += 1
45     end
46
47     return resp
48   end
49
50   # Check if a note is visible
51   def visible?
52     status != "hidden"
53   end
54
55   # Check if a note is closed
56   def closed?
57     not closed_at.nil?
58   end
59
60   # Return the author object, derived from the first comment
61   def author
62     self.comments.first.author
63   end
64
65   # Return the author IP address, derived from the first comment
66   def author_ip
67     self.comments.first.author_ip
68   end
69
70 private
71
72   # Fill in default values for new notes
73   def set_defaults
74     self.status = "open" unless self.attribute_present?(:status)
75   end
76 end