jam-cloud/ruby/lib/jam_ruby/models/online_presence.rb

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 :user_id, :service_type, :username
belongs_to :user, :class_name => "JamRuby::User", :foreign_key => "user_id"
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("user_id = ?", options[:id])
end
def self.create(current_user, options = {}, save = true)
auth_user(current_user, options)
raise StateError, "Missing required information" if options[:service_type].blank? || options[:username].blank?
up = OnlinePresence.new({
:user_id => current_user.id,
:service_type => options[:service_type],
:username => options[:username]
})
up.save! if save
up
end
def self.update(current_user, options = {})
auth_user(current_user, 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(current_user, options = {})
id = options[:id]
raise StateError, "Missing required information" if id.blank?
online_presence = OnlinePresence.find(id)
if online_presence.user_id != current_user.id
raise PermissionError, PERMISSION_MSG
end
unless online_presence.nil?
OnlinePresence.destroy(id)
end
end
private
def self.auth_user(current_user, options={})
raise PermissionError, PERMISSION_MSG if current_user.nil? || options[:user_id] != current_user.id
end
end
end