Skip to content

Instantly share code, notes, and snippets.

@dreamr
Created March 12, 2013 15:41
Show Gist options
  • Save dreamr/5143969 to your computer and use it in GitHub Desktop.
Save dreamr/5143969 to your computer and use it in GitHub Desktop.
module Models
module Concerns
module Bannable
extend ActiveSupport::Concern
included do
default_scope -> { where(banned_at: nil) }
end
def ban(reason=nil)
options = ban_attributes({ban_reason: reason, banned_at: DateTime.now})
do_bannable options
end
def unban
options = ban_attributes({ban_reason: nil, banned_at: nil})
do_bannable options
end
def banned?
self[:banned_at].present?
end
private
def do_bannable(ban_options)
update_attributes ban_options
if self.kind_of?(User)
ban_options.merge! user_id: id
self.class.send(:update_child_resources, ban_options)
end
end
def ban_attributes(options)
attributes = { banned_at: options[:banned_at] }
attributes.merge!(ban_reason: options[:ban_reason]) if respond_to?(:ban_reason)
end
module ClassMethods
def ban_all(ids, reason=nil)
ban_options = {ban: true, ids: ids, ban_reason: reason}
do_bannable ban_options
end
def unban_all(ids)
ban_options = {ban: false, ids: ids, ban_reason: nil}
do_bannable ban_options
end
def bannable_children
[Doctor, Dispensary, Lab, Event, Picture, Video, Review, CommunityPost,
ConversationMessage, WhatAreYouSmokingComment, Comment,
Forem::Topic, Forem::Post]
end
private
def do_bannable(ban_options)
bannable_update_call ban_options
update_child_resources ban_options if self.kind_of?(User)
end
def bannable_update_call(options)
fields_sql = "banned_at = ?"
field_values = [options[:banned_at]]
if respond_to?(:ban_reason)
fields_sql << ", ban_reason = ?"
field_values << options[:banned_at]
end
where_clause = if options[:user_id].present?
["user_id = ? ", options[:user_id]]
else
["id in (?)", options[:ids]]
end
unscoped.update_all [fields_sql, *field_values], where_clause
if self == Review && options[:user_id].present?
unscoped.where(user_id: options[:user_id]).map{|r| r.update_reviewable_average_rating}
end
end
def update_child_resources(options)
unless options[:ids].present? || options[:user_id].present?
raise "user_id or ids must be passed!"
end
bannable_children.each do |bannable|
bannable.send(:bannable_update_call, options)
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment