Skip to content

Commit

Permalink
Closes #20. Add installed callback for Middleware classes.
Browse files Browse the repository at this point in the history
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
```
  • Loading branch information
faultyserver committed Sep 22, 2016
1 parent fb42e20 commit 21dd00f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
5 changes: 4 additions & 1 deletion agency.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ def create_managers
def create_middlewares
instance_list = []
@middleware = configuration.middlewares.inject(nil) do |app, (klass, args, kwargs, config)|
klass.new(app, *args, **kwargs, &config).tap{ |inst| instance_list << inst }
klass.new(app, *args, **kwargs, &config).tap do |inst|
instance_list << inst
klass.installed(self)
end
end
# Some Middlewares will use background threads to process work. By
# sleeping for a short time between checks, those threads can work
Expand Down
11 changes: 11 additions & 0 deletions middleware.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ def self.register_handler namespace, event, &handler
end


# A callback to be run when a Middleware instance of this type is
# installed in an Agency.
def self.on_install &block
@installed_callback = block
end

def self.installed agency
@installed_callback&.call(agency)
end


attr_accessor :app, :storage


Expand Down

0 comments on commit 21dd00f

Please sign in to comment.