sourced-component 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: db15a3e8df75b3fd1e30d607d77d4a5812463f673c4530472ca32ad1b7bc66fc
4
- data.tar.gz: bde0065b4858b3a91898c2016068c1a1bec1d0d7cebc420f851cd51acce5269d
3
+ metadata.gz: 5cf658d39f33789d5924917599acc0c36e06158148183b7869e729487c5079f1
4
+ data.tar.gz: bce1383503980f2303c33cc9f23bf818c6852f1b9f3adc0d9dab5c66b69f3cdd
5
5
  SHA512:
6
- metadata.gz: 2268205f4ba2c92d53554e2b5a2b0d526d6c81df75cd193121a72bcf5ad921a7f4033baba1e5e5ba3bce8c2db133614a4e79742df4d35394974f1ba29bc7c69b
7
- data.tar.gz: bcd9972a3addfde922ad082991771357f96c6ac044f280c79c31255cbda1b0cea38ac2392454f91f39311edb697b49d292761d34401b9802da9690d5323e8484
6
+ metadata.gz: 3e0b9622663fa5ff24dcc17f7d893cb68b5526d918845e78c814b5b09ae1fe695cf07045d668742f1a4e9c0deb6e7a7e5628dfc49c161b92afd94304e925c90f
7
+ data.tar.gz: 4312500d49c431bbd3e0c5da81ee23b484a58147079c3e8f7286ebd1c27878840ad3386124028ec10c4dedf9a1c901008d4df4b2857c6797ea809be1b28d6282
data/CHANGELOG.md CHANGED
@@ -1,5 +1,7 @@
1
1
  ## [Unreleased]
2
2
 
3
+ - `#on_dir_load { |source, constants| }`: hear of every constant the files of a `#from_dir` define, installable or not, each time they install or reload
4
+ - `#install_dirs!`: load the files of every `#from_dir` and declare their components on an open tree, before `#prepare!`, so classes loaded earlier (ex. by Zeitwerk's `#eager_load`) can inject them
3
5
  - `#from_dir(glob)`: declare components from the files in a directory, with `.__install_component`, and reconfigure them when the tree's Zeitwerk loader reloads
4
6
  - `Sourced::Component::Installable`: the default `.__install_component`, `c.declare(self).factory(self)`, and `.__abstract_component!` for base classes
5
7
  - `#from_dir(glob, root: dir)`, rooted at the directory it scans: each top-level directory is a branch, reloaded together
data/README.md CHANGED
@@ -529,6 +529,14 @@ end
529
529
  - **Dependencies are relative to the component `#from_dir` was called on**, like the keys of `#inject`, so siblings are referenced by their full key (`c['logger'].key`).
530
530
  - **Constants that don't respond to `.__install_component` are skipped**, and so are files the loader ignores.
531
531
  - **Files are loaded on the root's `#prepare!`**, not by `#from_dir`, so the components they inject are declared by then. The loader must be set up before that. If a file raises, none of the directory's components are left declared, so booting again after fixing it works.
532
+ - **`#install_dirs!` loads them earlier**, on the open tree, for an app that loads classes injecting them before it prepares the tree, ex. with Zeitwerk's `#eager_load`. The tree stays open, and `#prepare!` skips the sources already installed. It's for the root, and raises `LockedComponentError` once the tree is prepared:
533
+
534
+ ```ruby
535
+ App.from_dir('system/**/*.rb', root: 'system')
536
+ loader.setup
537
+ App.install_dirs! # declares 'users.create', from system/users/create.rb
538
+ loader.eager_load # so a class elsewhere can inject 'users.create' as it loads
539
+ ```
532
540
  - **Files can inject each other's components**, whichever loads first. While `#from_dir` loads files, injecting a key that isn't declared yet is resolved once every file has declared its components, and one that's still missing raises `UndeclaredComponentError` (on a reload, rolling it back). Everywhere else, injecting an undeclared key raises straight away.
533
541
  - **Keys:** `App.from_dir('app/queries/**/*.rb', root: 'app/queries', namespace: 'queries')` keys `app/queries/users/search.rb` as `queries.users.search`. A glob without wildcards is a directory's own `.rb` files.
534
542
  - **A whole directory, without its name:** with `root:` set to the directory scanned and no `namespace:`, each top-level directory is a branch of its own:
@@ -545,6 +553,15 @@ end
545
553
  - **Branches can't overlap:** each `#from_dir` reconfigures its whole branch, so two whose branches nest raise `ArgumentError`, wherever in the tree they were registered. One rooted at the directory it scans overlaps any other. The branch must be a namespace with no mounted components, like any reconfigured branch.
546
554
  - **`#from_dir` is for open trees**, and raises `LockedComponentError` once the tree is prepared, including inside a `#reconfigure` block.
547
555
  - **The loader keeps each tree's reload hook**, since Zeitwerk can't remove `on_setup` callbacks. After teardown it does nothing, but a long-lived loader shared by many trees, ex. in tests, keeps them all in memory: give each tree its own loader.
556
+ - **`#on_dir_load` hears of every constant a directory's files define**, whether it installs components or not, so code that keeps its own record of some kind of class, ex. a registry of handlers, can follow the same scan and the same reloads:
557
+
558
+ ```ruby
559
+ App.on_dir_load do |source, constants|
560
+ handlers.replace(constants.select { |c| c.is_a?(Class) && c < Handler })
561
+ end
562
+ ```
563
+
564
+ It's called with the source and the constants, in file order, each time a source installs or reloads its files and the tree is reconfigured, so not for a reload that left the tree as it was. Listeners are set on the root, before the sources install (after, it raises `ArgumentError`, as the listener would miss what they loaded), and run in the order they were added. What one raises propagates from `#install_dirs!` or `#prepare!`, or goes to `on_error` on a reload. The tree is reconfigured either way.
548
565
  - **Classes outside the directory aren't re-declared.** A component elsewhere that captured a reloaded class in a provider keeps the old one: see [recycling](#recycling-components).
549
566
 
550
567
  ### Signal handlers
@@ -15,7 +15,7 @@ module Sourced
15
15
  INSTALL = :__install_component
16
16
  GLOB_CHARS = /[*?\[{]/
17
17
  DEFAULT_ON_ERROR = lambda do |error|
18
- Kernel.warn("[Sourced::Component] reloading components failed: #{error.class}: #{error.message}")
18
+ Kernel.warn("[Sourced::Component] reloading a from_dir directory failed: #{error.class}: #{error.message}")
19
19
  end
20
20
 
21
21
  # branch: the key every file is declared under, relative to the owner. Reconfigured on reload.
@@ -90,9 +90,14 @@ module Sourced
90
90
  # created by declaring into them.
91
91
  # Files can inject components that other files declare, whichever loads first: those are
92
92
  # resolved once every file is installed, and a missing one rolls the reconfiguration back.
93
+ # Once the tree is reconfigured, the root's #on_dir_load listeners get every file's constant.
93
94
  private def reconfigure!
95
+ loaded = nil
94
96
  installs = nil
95
- deferred = @owner.root.deferring_injections { installs = installables }
97
+ deferred = @owner.root.deferring_injections do
98
+ loaded = constants
99
+ installs = installables(loaded)
100
+ end
96
101
  keys = if branch.empty?
97
102
  claimed = installs.map { |key, _| key.split('.').first }.uniq
98
103
  (@claimed | claimed).select { |k| @owner.declared?(k) }
@@ -105,15 +110,20 @@ module Sourced
105
110
  deferred.each(&:resolve!)
106
111
  end
107
112
  @claimed = claimed if branch.empty?
113
+ @owner.root.dir_loaded!(self, loaded.map(&:last))
108
114
  end
109
115
 
110
- # [[key, constant]] for each file whose constant responds to .__install_component
111
- private def installables
116
+ # [[path, constant]] for each file the loader expects a constant in, loading it
117
+ private def constants
112
118
  files.filter_map do |path|
113
119
  cpath = @loader.cpath_expected_at(path)
114
- next unless cpath
120
+ [path, Object.const_get(cpath)] if cpath
121
+ end
122
+ end
115
123
 
116
- mod = Object.const_get(cpath)
124
+ # [[key, constant]] for each of +loaded+ that responds to .__install_component
125
+ private def installables(loaded)
126
+ loaded.filter_map do |path, mod|
117
127
  next unless mod.respond_to?(INSTALL)
118
128
 
119
129
  key = key_for(path.delete_suffix('.rb'))
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Sourced
4
4
  class Component
5
- VERSION = "0.1.2"
5
+ VERSION = "0.1.4"
6
6
  end
7
7
  end
@@ -79,6 +79,7 @@ module Sourced
79
79
  @order = nil
80
80
  @lock = Monitor.new
81
81
  @dir_sources = [] # see #from_dir
82
+ @dir_load_listeners = [] # see #on_dir_load
82
83
  @deferred_injections = nil # see #deferring_injections, on the root only
83
84
  end
84
85
 
@@ -397,7 +398,8 @@ module Sourced
397
398
  # app.loader = loader # once, on the root: see #loader=
398
399
  # app.from_dir('lib/**/*.rb') # lib/queries/users/search.rb => 'lib.queries.users.search'
399
400
  # app.from_dir('app/queries/**/*.rb', root: 'app/queries', namespace: 'queries')
400
- # Files are loaded on the root's #prepare!, so the components they inject are declared by then.
401
+ # Files are loaded on the root's #prepare!, so the components they inject are declared by then,
402
+ # or earlier with #install_dirs!.
401
403
  # When the loader reloads, the branch above the glob's first wildcard is reconfigured from the new
402
404
  # constants (see #reconfigure). A failed reload leaves the tree as it was and calls +on_error+.
403
405
  def from_dir(glob, root: Dir.pwd, namespace: nil, on_error: DirSource::DEFAULT_ON_ERROR)
@@ -422,6 +424,60 @@ module Sourced
422
424
  self
423
425
  end
424
426
 
427
+ # Call +block+ with a #from_dir source and the constants its files define, every one in file
428
+ # order, whether it installs components or not, each time the source installs or reloads them and
429
+ # the tree is reconfigured. For code that keeps its own record of the classes in a directory, ex.
430
+ # a registry of the ones of some kind, which a reload must keep up to date:
431
+ # app.on_dir_load do |source, constants|
432
+ # registry.replace(source, constants.select { |c| c.is_a?(Class) && c < Handler })
433
+ # end
434
+ # Set on the root, for the whole tree, before the sources install: once one has, it raises
435
+ # ArgumentError, since the listener would miss what it loaded. Listeners run in the order
436
+ # they were added. What one raises propagates from #install_dirs! or #prepare!, or goes to the
437
+ # source's +on_error+ on a reload, the tree reconfigured either way.
438
+ # @return [self]
439
+ def on_dir_load(&block)
440
+ raise ArgumentError, 'on_dir_load needs a block' unless block
441
+
442
+ synchronize do
443
+ raise SubcomponentError, "#{path} is mounted in another component: call on_dir_load on the root" unless root?
444
+ if (installed = all_dir_sources.find(&:installed?))
445
+ raise ArgumentError, "on_dir_load: #{installed.inspect} has already installed, so the listener " \
446
+ 'would miss what it loaded. Add it before #install_dirs! or #prepare!'
447
+ end
448
+
449
+ @dir_load_listeners << block
450
+ end
451
+ self
452
+ end
453
+
454
+ # Called by a DirSource on the root, once its files are loaded and the tree reconfigured. Not for
455
+ # apps: see #on_dir_load
456
+ # @api private
457
+ def dir_loaded!(source, constants)
458
+ synchronize { @dir_load_listeners.dup }.each { |listener| listener.call(source, constants) }
459
+ end
460
+
461
+ # Load the files of every #from_dir in the tree now, on an open tree, rather than on #prepare!,
462
+ # and declare their components. The tree stays open, so more can still be declared and
463
+ # implemented, and #prepare! skips the sources already installed. For an app that loads classes
464
+ # injecting those components before it prepares the tree, ex. with Zeitwerk's #eager_load:
465
+ # app.from_dir('system/**/*.rb', root: 'system')
466
+ # loader.setup
467
+ # app.install_dirs! # declares 'users.create', from system/users/create.rb
468
+ # loader.eager_load # so web/ classes can inject it
469
+ # The loader must be set up. If a file raises, none of the directory's components are left
470
+ # declared, and calling it again (or #prepare!) retries.
471
+ def install_dirs!
472
+ raise_mounted!
473
+ synchronize do
474
+ raise LockedComponentError, "can't install directories into a locked component" if locked?
475
+
476
+ [self, *index.values].each { |n| n.install_dir_sources! }
477
+ end
478
+ self
479
+ end
480
+
425
481
  # A node under this component, by relative key
426
482
  def node(ckey)
427
483
  index.fetch(ckey.to_s) { raise UndeclaredComponentError, "#{ckey} is not declared in #{path || 'this component'}" }
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: sourced-component
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.2
4
+ version: 0.1.4
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ismael Celis