Skip to content

Instantly share code, notes, and snippets.

@sycobuny
Created August 2, 2011 03:04
Show Gist options
  • Save sycobuny/1119520 to your computer and use it in GitHub Desktop.
Save sycobuny/1119520 to your computer and use it in GitHub Desktop.
Cool DB stuff
def add_user_access(user, *flags_to_add)
# normalize arguments into a form we'll recognize
flags_to_add.collect! { |flag| flag.to_sym }
id = user.to_i
# backup our arguments in case we need to restore to them later
flags = user_flags(id)
flags_backup = flags.dup
flag_lookup_backup = {}
flags_to_add.each do |flag|
flag_lookup_backup[flag] = flag_users(flag).dup
end
begin
$db.transaction do
flags_to_add.each do |flag|
# don't bother adding a flag we've already got
next if flags.include?(flag.to_sym)
# otherwise, make a new ChannelFlag object and set it up
channel_user_flag = ChannelUserFlag.new
channel_user_flag.channel = self
channel_user_flag.user_id = id
channel_user_flag.flag = flag.to_s
# add the flags to our cache and the DB
flags << flag
add_channel_user_flag(channel_user_flag)
flag_lookup = flag_users(flag)
flag_lookup << id unless flag_lookup.include?(id)
end
end
rescue Exception => e
# rollback changes to our cache if we couldn't save
@user_lookup[id] = flags_backup
flag_lookup_backup.each do |flag, users|
@flag_lookup[flag] = users
end
# reraise cause we don't know for sure how to proceed from here
raise e
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment