67 lines
2.2 KiB
Ruby
67 lines
2.2 KiB
Ruby
module JamRuby
|
|
class OnlinePresence < ActiveRecord::Base
|
|
|
|
PERMISSION_MSG = "You do not have permission to perform this operation."
|
|
|
|
attr_accessible :player_id, :service_type, :username
|
|
belongs_to :player, polymorphic: true
|
|
|
|
validates :service_type, presence:true, length: {maximum: 100}
|
|
validates :username, presence:true, length: {maximum: 100}
|
|
|
|
validate :username_service_type_unique
|
|
|
|
def username_service_type_unique
|
|
match = OnlinePresence.exists?(:username => self.username, :service_type => self.service_type)
|
|
raise ConflictError, "Username #{self.username} is already associated with a #{self.service_type} account" if match
|
|
end
|
|
|
|
def self.index(options = {})
|
|
raise StateError, "The user is not specified." if options[:id].blank?
|
|
OnlinePresence.where("player_id = ?", options[:id])
|
|
end
|
|
|
|
def self.create(player, options = {}, save = true)
|
|
auth_player(player, options)
|
|
raise StateError, "Missing required information" if options[:service_type].blank? || options[:username].blank?
|
|
|
|
up = OnlinePresence.new({
|
|
:player_id => player.id,
|
|
:service_type => options[:service_type],
|
|
:username => options[:username]
|
|
})
|
|
|
|
up.save! if save
|
|
up
|
|
end
|
|
|
|
def self.update(player, options = {})
|
|
auth_player(player, options)
|
|
raise StateError, "Missing required information" if options[:service_type].blank? || options[:username].blank? || options[:id].blank?
|
|
|
|
up = OnlinePresence.find(options[:id])
|
|
up.service_type = options[:service_type]
|
|
up.username = options[:username]
|
|
up.save!
|
|
end
|
|
|
|
def self.delete(player, options = {})
|
|
id = options[:id]
|
|
raise StateError, "Missing required information" if id.blank?
|
|
online_presence = OnlinePresence.find(id)
|
|
|
|
if online_presence.player_id != player.id
|
|
raise JamPermissionError, PERMISSION_MSG
|
|
end
|
|
|
|
unless online_presence.nil?
|
|
OnlinePresence.destroy(id)
|
|
end
|
|
end
|
|
|
|
private
|
|
def self.auth_player(player, options={})
|
|
raise JamPermissionError, PERMISSION_MSG if player.nil? || options[:player_id] != player.id
|
|
end
|
|
end
|
|
end |