diff --git a/lib/discourse_chat/helper.rb b/lib/discourse_chat/helper.rb index 82c76d1..34bf1b9 100644 --- a/lib/discourse_chat/helper.rb +++ b/lib/discourse_chat/helper.rb @@ -41,6 +41,16 @@ module DiscourseChat return text end + # Delete a rule based on its (1 based) index as seen in the + # status_for_channel function + def self.delete_by_index(provider, channel, index) + rules = DiscourseChat::Rule.all_for_channel(provider, channel) + + return false if index < 1 or index > rules.size + + return :deleted if rules[index-1].destroy + end + # Create a rule for a specific channel # Designed to be used by provider's "Slash commands" # Will intelligently adjust existing rules to avoid duplicates diff --git a/spec/lib/discourse_chat/helper_spec.rb b/spec/lib/discourse_chat/helper_spec.rb index f3c721f..6cd73d7 100644 --- a/spec/lib/discourse_chat/helper_spec.rb +++ b/spec/lib/discourse_chat/helper_spec.rb @@ -56,6 +56,59 @@ RSpec.describe DiscourseChat::Manager do end + describe '.delete_by_index' do + let(:category2) {Fabricate(:category)} + let(:category3) {Fabricate(:category)} + + it 'deletes the correct rule' do + # Three identical rules, with different categories + # Status will be sorted by category id, so they should + # be in this order + rule1 = DiscourseChat::Rule.new({provider: 'slack', + channel: '#general', + filter: 'watch', + category_id: category.id, + tags: [tag1.name, tag2.name] + }).save! + rule2 = DiscourseChat::Rule.new({provider: 'slack', + channel: '#general', + filter: 'watch', + category_id: category2.id, + tags: [tag1.name, tag2.name] + }).save! + rule3 = DiscourseChat::Rule.new({provider: 'slack', + channel: '#general', + filter: 'watch', + category_id: category3.id, + tags: [tag1.name, tag2.name] + }).save! + + expect(DiscourseChat::Rule.all.size).to eq(3) + + expect(DiscourseChat::Helper.delete_by_index('slack','#general',2)).to eq(:deleted) + + expect(DiscourseChat::Rule.all.size).to eq(2) + expect(DiscourseChat::Rule.all.map(&:category_id)).to contain_exactly(category.id, category3.id) + end + + it 'fails gracefully for out of range indexes' do + rule1 = DiscourseChat::Rule.new({provider: 'slack', + channel: '#general', + filter: 'watch', + category_id: category.id, + tags: [tag1.name, tag2.name] + }).save! + + expect(DiscourseChat::Helper.delete_by_index('slack','#general',-1)).to eq(false) + expect(DiscourseChat::Helper.delete_by_index('slack','#general',0)).to eq(false) + expect(DiscourseChat::Helper.delete_by_index('slack','#general',2)).to eq(false) + + expect(DiscourseChat::Helper.delete_by_index('slack','#general',1)).to eq(:deleted) + end + + + end + describe '.smart_create_rule' do it 'creates a rule when there are none' do @@ -141,8 +194,6 @@ RSpec.describe DiscourseChat::Manager do expect(val).to eq(false) end - - end end \ No newline at end of file