|
| 1 | +--- |
| 2 | +title: Hooks |
| 3 | +layout: gem-single |
| 4 | +name: dry-system |
| 5 | +--- |
| 6 | + |
| 7 | +There are a few lifecycle events that you can hook into if you need to ensure things happen in a particular order. |
| 8 | + |
| 9 | +Hooks are executed within the context of the container instance. |
| 10 | + |
| 11 | +### `configure` Event |
| 12 | + |
| 13 | +You can register a callback to fire after the container is configured, which happens one of three ways: |
| 14 | + |
| 15 | +1. The `configure` method is called on the container |
| 16 | +2. The `configured!` method is called |
| 17 | +3. The `finalize!` method is called when neither of the other two have been |
| 18 | + |
| 19 | +```ruby |
| 20 | +class MyApp::Container < Dry::System::Container |
| 21 | + after(:configure) do |
| 22 | + # do something here |
| 23 | + end |
| 24 | +end |
| 25 | +``` |
| 26 | + |
| 27 | +### `register` Event |
| 28 | + |
| 29 | +Most of the time, you will know what keys you are working with ahead of time. But for certain cases you may want to |
| 30 | +react to keys dynamically. |
| 31 | + |
| 32 | +```ruby |
| 33 | +class MyApp::Container < Dry::System::Container |
| 34 | + use :monitoring |
| 35 | + |
| 36 | + after(:register) do |key| |
| 37 | + next unless key.end_with?(".gateway") |
| 38 | + |
| 39 | + monitor(key) do |event| |
| 40 | + resolve(:logger).debug(key:, method: event[:method], time: event[:time]) |
| 41 | + end |
| 42 | + end |
| 43 | +end |
| 44 | +``` |
| 45 | + |
| 46 | +Now let's say you register `api_client.gateway` into your container. Your API methods will be automatically monitored |
| 47 | +and their timing measured and logged. |
| 48 | + |
| 49 | +### `finalize` Event |
| 50 | + |
| 51 | +Finalization is the point at which the container is made ready, such as booting a web application. |
| 52 | + |
| 53 | +The following keys are loaded in sequence: |
| 54 | + |
| 55 | +1. Providers |
| 56 | +2. Auto-registered components |
| 57 | +3. Manually-registered components |
| 58 | +4. Container imports |
| 59 | + |
| 60 | +At the conclusion of this process, the container is frozen thus preventing any further changes. This makes the |
| 61 | +`finalize` event quite important: it's the last call before your container will disallow mutation. |
| 62 | + |
| 63 | +Unlike the previous events, you can register before hooks in addition to after hooks. |
| 64 | + |
| 65 | +The after hooks will run immediately prior to the container freeze. This allows you to enumerate the container keys |
| 66 | +while they can still be mutated, such as with `decorate` or `monitor`. |
| 67 | + |
| 68 | +```ruby |
| 69 | +class MyApp::Container < Dry::System::Container |
| 70 | + before(:finalize) do |
| 71 | + # Before system boot, no keys registered yet |
| 72 | + end |
| 73 | + |
| 74 | + after(:finalize) do |
| 75 | + # After system boot, all keys registered |
| 76 | + end |
| 77 | +end |
| 78 | +``` |
0 commit comments