lib/cinch/plugins/karma/karma.rb in cinch-karma-0.0.1 vs lib/cinch/plugins/karma/karma.rb in cinch-karma-1.0.0

- old
+ new

@@ -1,5 +1,6 @@ +require 'cinch' require 'cinch-cooldown' require 'cinch-storage' module Cinch::Plugins class Karma @@ -20,49 +21,52 @@ end def listen(m) if m.message.match(/\S+[\+\-]{2}/) channel = m.channel.name - @storage.data[channel] = Hash.new unless @storage.data.key?(channel) - updated = false - m.message.scan(/.*?((\w+)|\((.+?)\))(\+\+|--)(\s|\z)/).each do |karma| - debug "#{karma}" + # Scan messages for multiple karma items + m.message.scan(/(\s|\A)(\w+|\(.+?\))(\+\+|--)(\s|\z)/).each do |karma| + process_karma(channel, karma[1].gsub(/\(|\)/, '').downcase, karma[2]) + end - if karma[0] - item = karma[1] || karma[2] - item.downcase! + @storage.synced_save(@bot) + end + end - @storage.data[channel][item] = 0 unless @storage.data[channel].key?(item) + def execute(m, item) + return if sent_via_pm?(m) - if karma[3] == '++' - @storage.data[channel][item] += 1 - updated = true - elsif karma[3] == '--' - @storage.data[channel][item] -= 1 - updated = true - else - debug 'something went wrong matching karma!' - end - end - end + channel = m.channel.name + item.downcase! + init_karma(channel, item) - if updated - synchronize(:karma_save) do - @storage.save - end - end + m.reply "Karma for #{item} is #{@storage.data[channel][item]}" + end + + private + + def process_karma(channel, item, operation) + # Ensure the item's Karma has been init + init_karma(channel, item) + + case operation + when '++' + @storage.data[channel][item] += 1 + when '--' + @storage.data[channel][item] -= 1 end end - def execute(m, item) + def sent_via_pm?(m) if m.channel.nil? - m.user.msg "You must use that command in the main channel." - return + m.reply "You must use that command in the main channel." + return true end + end - @storage.data[m.channel.name] = Hash.new unless @storage.data.key?(m.channel.name) - karma = @storage.data[m.channel.name][item.downcase] || 0 - m.reply "Karma for #{item} is #{karma}" + def init_karma(channel, item = nil) + @storage.data[channel] ||= Hash.new + @storage.data[channel][item] ||= 0 unless item.nil? end end end