Advertisement
hocikto19

module followable

Jul 16th, 2016
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 0.90 KB | None | 0 0
  1. module Followable
  2.   extend ActiveSupport::Concern
  3.   include ActiveModel::Model
  4.  
  5.   included do
  6.  
  7.     has_many :followers_followed, foreign_key: 'followed_id'
  8.     has_many :users, through: :followers_followed
  9.     has_many :messages, foreign_key: 'followable_id'
  10.  
  11.     after_update do
  12.       message = self.create_message
  13.       self.followers.each do |user|
  14.         MessagesUser.create message: message, user: user
  15.       end
  16.     end
  17.  
  18.   end
  19.  
  20.   def create_message
  21.     Message.create content: 'Yay, a message', followable_id: self.id, followable_type_code: self.class.table_name
  22.   end
  23.  
  24.   def followers
  25.     self.users.where('followers_followed.followable_type_code = ?', self.class.table_name)
  26.   end
  27.  
  28.   def is_followed?(user)
  29.     return self.followers.include? user if user.class == User
  30.     return self.followers.any? { |follower| follower.id == user } if user.class == Fixnum
  31.     false
  32.   end
  33.  
  34. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement