Skip to content

Instantly share code, notes, and snippets.

@dreamr
Created March 1, 2013 00:47
Show Gist options
  • Save dreamr/5061528 to your computer and use it in GitHub Desktop.
Save dreamr/5061528 to your computer and use it in GitHub Desktop.
module Bannable
extend ActiveSupport::Concern
included do
extend ClassMethods
default_scope where("banned_at IS NULL")
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 un_all(ids)
ban_options = {ban: false, ids: ids, ban_reason: nil}
do_bannable ban_options
end
private
def do_bannable(ban_options)
update_call ban_options
update_child_resources ban_options if self.kind_of?(User)
end
def update_call(options)
fields_sql = "banned_at = ?"
fields_sql = fields_sql + ", ban_reason = ?" if respond_to?(:ban_reason)
field_values = [options[:banned_at]]
field_values = [field_values + options[:banned_at]] if respond_to?(:ban_reason)
where_clause = options[:user_id].present? ? ["user_id = ? ", options[:user_id]] :
["id in (?)", options[:ids]]
update_all [fields_sql, *field_values], where_clause
end
def update_child_resources(options)
unless options[:ids].present? || options[:user_id].present?
raise "user_id or ids must be passed!"
end
%w( Dispensary Doctor Lab
Picture Video Review HelpfulReview
ConversationMessage
WhatAreYouSmokingComment Event CommunityPost ).each do |bannable|
bannable.constantize.send(:update_call, options)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment