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 attr_reader :user, :args
def self.handlers def self.sorted_handlers
@handlers ||= Set.new @sorted_handlers ||= clear_handlers!
end end
def self.add_handler(&block) def self.handlers
handlers << block 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 end
def self.default_handler(manager) def self.default_handler(manager)
@ -32,8 +41,6 @@ class NewPostManager
handlers.size > 1 handlers.size > 1
end end
add_handler {|manager| default_handler(manager) }
def initialize(user, args) def initialize(user, args)
@user = user @user = user
@args = args.delete_if {|_, v| v.nil?} @args = args.delete_if {|_, v| v.nil?}

View File

@ -56,6 +56,34 @@ describe NewPostManager do
end end
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 context "extensibility" do
before do before do
@ -78,8 +106,7 @@ describe NewPostManager do
end end
after do after do
NewPostManager.handlers.delete(@counter_handler) NewPostManager.clear_handlers!
NewPostManager.handlers.delete(@queue_handler)
end end
it "has a queue enabled" do it "has a queue enabled" do