Handlers can be added with a priority

This commit is contained in:
Robin Ward 2015-04-28 13:53:05 -04:00
parent 5783e908ea
commit cf0c2d09d4
2 changed files with 42 additions and 8 deletions

View File

@ -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?}

View File

@ -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