Skip to content
Snippets Groups Projects
Forked from PortalMEC / portalmec
396 commits behind the upstream repository.
sociable.rb 1.55 KiB

# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with portalmec.  If not, see <http://www.gnu.org/licenses/>.

module Sociable
  extend ActiveSupport::Concern

  included do
    has_many :views, as: :viewable, dependent: :destroy
    has_many :likes, as: :likeable, dependent: :destroy
    has_many :shares, as: :shareable, dependent: :destroy
  end

  def liked?(user)
    !likes.where(user: user).blank?
  end

  def like(user)
    Like.create(user: user, likeable: self)
  end

  def dislike(user)
    Like.where(user: user, likeable: self).destroy_all
  end

  def share(user)
    Share.create(user: user, shareable: self)
  end

  def shared?(user)
    !Share.where(user: user, shareable: self).blank?
  end

  def view(user, ip)
    View.create(user: user, ip: ip, viewable: self)
  end

  def viewed?(user)
    !View.where(user: user, viewable: self).blank?
  end
end