Sha256: ce717eb00b27304640f48509bb447ef1ad0d4a00e6a3468ed204335852828e0f

Contents?: true

Size: 1.41 KB

Versions: 3

Compression:

Stored size: 1.41 KB

Contents

module Formol
  class Topic::Track < ActiveRecord::Base
    #Security
    attr_protected  :user_id, :topic_id, :forum_id, :marked_at
    attr_readonly   :user_id, :topic_id, :forum_id
    
    #Association
    belongs_to :user,   :class_name => Formol.config.user_class
    belongs_to :topic
    belongs_to :forum

    #Validations
    validates :user_id,   :presence => true
    validates :topic_id,  :presence => true
    validates :forum_id,  :presence => true
    validates :marked_at, :presence => true
    
    #Callbacks
    before_validation :assign_forum,    :on => :create
    before_validation :touch_marked_at
    
    #Business methods
    
    class << self
      # mark a given topic for a given user
      # if track already exists, it will be updated otherwhise it will be created
      # handle nil user if forum is browsed without being connected
      def mark_topic_for_user(topic, user)
        return nil if user.nil?
        
        track = find_or_initialize_by_topic_id_and_user_id(topic.id, user.id)
        track.mark
        
        track
      end
    end
    
    def mark
      save
    end
    
    private
    
    #Callback methods
    
    # assigns forum from topic
    # convenient to know if a forum is read or not
    def assign_forum
      self.forum = topic.forum if topic
    end
    
    # assigns current time to marked_at
    def touch_marked_at
      self.marked_at = Time.now
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
formol-0.0.6 app/models/formol/topic/track.rb
formol-0.0.5 app/models/formol/topic/track.rb
formol-0.0.4 app/models/formol/topic/track.rb