Skip to content

Commit 21dd00f

Browse files
committed
Closes #20. Add installed callback for Middleware classes.
Middleware classes can now define an `on_install` block to be called when an instance of it is created and added to the middleware stack of an agency. The callback will receive the agency as the only argument, and will be executed in the context of the Middleware class (not the instance. This is not set in stone, comments are welcome). Since #20 was opened, the `Schemable` module was implemented, changing the way attributes are added to objects. Because of this, and because of slightly different opinions on implementation, the actual code to achieve the same result as the example given in the issue (adding a `neighborhood` attribute to `Shark::Vehicle`) would simply be ``` class NeighborhoodMiddleware < Shark::Middleware on_install do |agency| Shark::Vehicle.attribute :neighborhood, type: String, nilable: true end end ```
1 parent fb42e20 commit 21dd00f

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

agency.rb

+4-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,10 @@ def create_managers
6565
def create_middlewares
6666
instance_list = []
6767
@middleware = configuration.middlewares.inject(nil) do |app, (klass, args, kwargs, config)|
68-
klass.new(app, *args, **kwargs, &config).tap{ |inst| instance_list << inst }
68+
klass.new(app, *args, **kwargs, &config).tap do |inst|
69+
instance_list << inst
70+
klass.installed(self)
71+
end
6972
end
7073
# Some Middlewares will use background threads to process work. By
7174
# sleeping for a short time between checks, those threads can work

middleware.rb

+11
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,17 @@ def self.register_handler namespace, event, &handler
4040
end
4141

4242

43+
# A callback to be run when a Middleware instance of this type is
44+
# installed in an Agency.
45+
def self.on_install &block
46+
@installed_callback = block
47+
end
48+
49+
def self.installed agency
50+
@installed_callback&.call(agency)
51+
end
52+
53+
4354
attr_accessor :app, :storage
4455

4556

0 commit comments

Comments
 (0)