1 # == Schema Information
 
   5 #  id          :bigint           not null, primary key
 
   6 #  latitude    :integer          not null
 
   7 #  longitude   :integer          not null
 
   8 #  tile        :bigint           not null
 
   9 #  updated_at  :datetime         not null
 
  10 #  created_at  :datetime         not null
 
  11 #  status      :enum             not null
 
  13 #  description :text             default(""), not null
 
  19 #  index_notes_on_description             (to_tsvector('english'::regconfig, description)) USING gin
 
  20 #  index_notes_on_user_id_and_created_at  (user_id,created_at) WHERE (user_id IS NOT NULL)
 
  21 #  notes_created_at_idx                   (created_at)
 
  22 #  notes_tile_status_idx                  (tile,status)
 
  23 #  notes_updated_at_idx                   (updated_at)
 
  27 #  notes_user_id_fkey  (user_id => users.id)
 
  30 class Note < ApplicationRecord
 
  33   belongs_to :author, :class_name => "User", :foreign_key => "user_id", :optional => true
 
  35   has_many :comments, -> { left_joins(:author).where(:visible => true, :users => { :status => [nil, "active", "confirmed"] }).order(:created_at) }, :class_name => "NoteComment", :foreign_key => :note_id
 
  36   has_many :all_comments, -> { left_joins(:author).order(:created_at) }, :class_name => "NoteComment", :foreign_key => :note_id, :inverse_of => :note
 
  37   has_many :subscriptions, :class_name => "NoteSubscription"
 
  38   has_many :subscribers, :through => :subscriptions, :source => :user
 
  40   validates :id, :uniqueness => true, :presence => { :on => :update },
 
  41                  :numericality => { :on => :update, :only_integer => true }
 
  42   validates :latitude, :longitude, :numericality => { :only_integer => true }
 
  43   validates :closed_at, :presence => true, :if => proc { :status == "closed" }
 
  44   validates :status, :inclusion => %w[open closed hidden]
 
  46   validate :validate_position
 
  48   scope :visible, -> { where.not(:status => "hidden") }
 
  49   scope :invisible, -> { where(:status => "hidden") }
 
  51   after_initialize :set_defaults
 
  53   DEFAULT_FRESHLY_CLOSED_LIMIT = 7.days
 
  55   # Sanity check the latitude and longitude and add an error if it's broken
 
  57     errors.add(:base, "Note is not in the world") unless in_world?
 
  62     self.status = "closed"
 
  63     self.closed_at = Time.now.utc
 
  74   # Check if a note is visible
 
  79   # Check if a note is closed
 
  85     return false unless closed?
 
  87     Time.now.utc < freshly_closed_until
 
  90   def freshly_closed_until
 
  91     return nil unless closed?
 
  93     closed_at + DEFAULT_FRESHLY_CLOSED_LIMIT
 
  96   # Return the note's description
 
  98     RichText.new("text", super)
 
 103   # Fill in default values for new notes
 
 105     self.status = "open" unless attribute_present?(:status)