diff --git a/lib/new_post_manager.rb b/lib/new_post_manager.rb index cde9357f6..9ada9820a 100644 --- a/lib/new_post_manager.rb +++ b/lib/new_post_manager.rb @@ -11,12 +11,21 @@ class NewPostManager attr_reader :user, :args - def self.handlers - @handlers ||= Set.new + def self.sorted_handlers + @sorted_handlers ||= clear_handlers! end - def self.add_handler(&block) - handlers << block + def self.handlers + sorted_handlers.map {|h| h[:proc]} + end + + def self.clear_handlers! + @sorted_handlers = [{ priority: 0, proc: method(:default_handler) }] + end + + def self.add_handler(priority=0, &block) + sorted_handlers << { priority: priority, proc: block } + @sorted_handlers.sort_by! {|h| -h[:priority]} end def self.default_handler(manager) @@ -32,8 +41,6 @@ class NewPostManager handlers.size > 1 end - add_handler {|manager| default_handler(manager) } - def initialize(user, args) @user = user @args = args.delete_if {|_, v| v.nil?} diff --git a/spec/components/new_post_manager_spec.rb b/spec/components/new_post_manager_spec.rb index 9bc7e6061..abc03a9de 100644 --- a/spec/components/new_post_manager_spec.rb +++ b/spec/components/new_post_manager_spec.rb @@ -56,6 +56,34 @@ describe NewPostManager do end end + context "extensibility priority" do + + after do + NewPostManager.clear_handlers! + end + + let(:default_handler) { NewPostManager.method(:default_handler) } + + it "adds in order by default" do + handler = ->{ nil } + + NewPostManager.add_handler(&handler) + expect(NewPostManager.handlers).to eq([default_handler, handler]) + end + + it "can be added in high priority" do + a = ->{ nil } + b = ->{ nil } + c = ->{ nil } + + NewPostManager.add_handler(100, &a) + NewPostManager.add_handler(50, &b) + NewPostManager.add_handler(101, &c) + expect(NewPostManager.handlers).to eq([c, a, b, default_handler]) + end + + end + context "extensibility" do before do @@ -78,8 +106,7 @@ describe NewPostManager do end after do - NewPostManager.handlers.delete(@counter_handler) - NewPostManager.handlers.delete(@queue_handler) + NewPostManager.clear_handlers! end it "has a queue enabled" do