nero 0.6.0 → 0.7.0.rc3

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: 136899b1a5b7fd355608891703ad0e8b0c628dfcb3ae74d9a5344fb0a78b41b8
4
- data.tar.gz: 47fce2793b077af0a637d7cac6a5e31b471c16bbbff71561f97bdf4aa904a3d5
3
+ metadata.gz: b92e0389403dd9f57c6c0c476e558b6ab1acb5bdeaf29d158965504cb79d8c9e
4
+ data.tar.gz: 403346da5deef774a8d9d1c356fa001f3e0449838e81a0100c1f9d4d8296a37f
5
5
  SHA512:
6
- metadata.gz: 979f099766b6c33577346e608fa8e82f890d4d3ef5b49913a142cdbcb7385ecff78776882e5ee78420f0b285388972aef8e6c4c980d4aff120b8c142efec2212
7
- data.tar.gz: e43d9f3916bfc43b3abe49939b3953a72679fec64e8de4de5b682600d6d5ef2f66f97557e262a5558046c9e332532bc908a4317d4a114bc46754d9ff60d3242c
6
+ metadata.gz: 1c05f1425114806eaa2ef5d4b5415470e53246f507b84428e144d701c807c22bd35968ed27ae486d3bd10df88e00da48962c91a1e87bb35571a346daf1389e0f
7
+ data.tar.gz: 023da599d1feccf02b3884c66545a9504671624943effb02309dc6926e7b933a34877505a202dee9ea1ad175d998202c8474b0287b177b296a9d836ecd858910
data/.envrc CHANGED
@@ -1 +1,3 @@
1
- PATH_add bin
1
+ PATH_add bin
2
+
3
+ source_env_if_exists .envrc.local
data/.irbrc ADDED
@@ -0,0 +1,4 @@
1
+ puts "Loading #{__FILE__}"
2
+ # Put overrides/additions in '_irbrc' (see _irbrc.example)
3
+ IRB.conf[:HISTORY_FILE] = "tmp/.irb_history"
4
+ IRB.conf[:HISTORY] = -1 # all of it
data/CHANGELOG.md CHANGED
@@ -1,5 +1,77 @@
1
+ Changes can be:
2
+
3
+ * ✨ Features
4
+ * ⚠️ Breaking
5
+ * 🐛 Bug Fixes
6
+ * 🛠️ Developer
7
+ * 🛡️ Security
8
+
1
9
  ## [Unreleased]
2
- ...
10
+
11
+ Total refactor and so quite some breaking changes. See [UPGRADING.md](UPGRADING.md) for a step-by-step guide from 0.6.
12
+
13
+ ## Breaking Changes
14
+
15
+ - **`Nero.load` / `Nero.load_file` now return string keys**, like `YAML.load` (0.6: symbol keys). `Nero.load(...)[:foo]` silently gives `nil`: use `symbolize_names: true`, or `Nero.config_for` (symbol keys, like Rails). They raise `Nero::ParseError` with all errors at once; `Nero::Parser#parse`/`#parse_file` return a `Result` instead.
16
+ - Nero.configure / Nero.configuration removed — custom tags are now registered via a block passed to parse/parse_file/config_for:
17
+ ```ruby
18
+ # Before
19
+ Nero.configure { |c| c.add_tag("rot/13", klass: RotTag[n: 13]) }
20
+ Nero.load("secret: !rot/13 uryyb")
21
+
22
+ # After
23
+ Nero.parse("secret: !rot/13 uryyb") { |c| c.add_tag("rot/13", RotTag.new(n: 13)) }
24
+ ```
25
+ - `Nero::Config` removed — results are plain Hashes (string keys) instead of a Config subclass with DigExt/dig!.
26
+ - `Nero::BaseTag` API changed — tags now implement resolve(args, context:) instead of accessing coder/ctx. Tag options are passed via initialize instead of init_options.
27
+ - !ref syntax changed — dot-notation `!ref base.url` is the preferred form. The sequence form `!ref [base, url]` still works but is deprecated (prints a warning) and will be removed in 0.8.
28
+ - root: option replaces root:/env: and uses string keys (e.g. root: :development matches the string key "development").
29
+ - Keys: `Nero.load`/`load_file` give string keys (`symbolize_names: true` for symbols), `Nero.config_for` gives symbol keys.
30
+ - !uri and !path tags removed — !uri is gone entirely; !path is no longer a built-in.
31
+ - `Nero::PathRootTag` renamed to `Nero::RootPathTag` with a new constructor API.
32
+ - `!path/rails_root` is only available with Rails (`nero/rails`, loaded by the Railtie); `!path/git_root` stays built in.
33
+ - `!secret_key_base` (0.7.0 release candidates only) removed. Read it in Ruby instead (`Rails.application.secret_key_base`, or better `Rails.application.key_generator.generate_key("purpose")`), or register it as a one-line custom tag.
34
+ - !str/format changed — now also available as !format; the map form (fmt: key) is replaced by a sequence with named-parameter hashes: !format ["http://%<host>s", host: !ref host].
35
+ - load_config removed (was already deprecated).
36
+ - Nero::Util removed — deep_symbolize_keys and deep_transform_values are no longer needed.
37
+ - Requires Ruby >= 3.3 (the oldest Ruby still receiving security fixes).
38
+ - `!env?/bool` (formerly `!env/bool?`) returns `nil` when the variable is not set (0.6: `false`): missing is not the same as "no". Use a fallback for a default: `!env?/bool [DEBUG, false]`, or `!env/bool [DEBUG, false]`.
39
+ - `!env/bool` is strict: only `1/y/yes/true/on` (true) and `0/n/no/false/off` (false) are accepted, case-insensitive and ignoring surrounding whitespace. Anything else (including an empty value) is a parse error. Before, the check was not anchored, so any value containing e.g. a `y` (`maybe`, `anything`) was `true`.
40
+
41
+ ## Security
42
+
43
+ - MFA required to publish this gem.
44
+ - YAML can no longer instantiate arbitrary Ruby objects (`!ruby/object:...`). Like `YAML.load`, `Nero.load`/`load_file` only allow `Symbol`; `Nero.config_for` also allows `Date` and `Time` (unlike Rails' `config_for`, which uses `YAML.unsafe_load`). Anything else is a parse error; allow more with `permitted_classes:`, e.g. `Nero.load(yaml, permitted_classes: %w[Symbol Date])`. Aliases (anchors) stay allowed.
45
+
46
+ ## Features
47
+
48
+ - `!env/list` / `!env?/list`: a comma-separated env value as an Array (`a.com, b.com` → `["a.com", "b.com"]`); the fallback can be a sequence: `!env/list [HOSTS, [localhost]]`.
49
+ - `!env/ip` / `!env?/ip`: an env value as `IPAddr` (address or CIDR range).
50
+
51
+ - `!ip`: an `IPAddr` from an address or CIDR range (`!ip 10.0.0.0/8`); a sequence of one nests a tag (`!ip [!env ADMIN_IP]`). Invalid addresses are a parse error.
52
+
53
+ - `NERO_ALL_OPTIONAL` (formerly `NERO_ENV_ALL_OPTIONAL`) also covers Rails `!credentials`: a missing env var or credential resolves to its fallback or `nil` instead of an error. Handy for tasks that boot the app without its config, e.g. `rails assets:precompile` or `rails credentials:edit`. Also available as a parser option: `Nero.load(yaml, all_optional: true)`. Only a non-empty value switches it on (`NERO_ALL_OPTIONAL=` is off). `NERO_ENV_ALL_OPTIONAL` still works, with a deprecation warning, until 0.8.
54
+
55
+ - `Nero.parse` / `Nero.parse_file` (0.7.0 release candidates) are deprecated aliases of `Nero.load` / `Nero.load_file`; removed in 0.8.
56
+
57
+ - Deprecation warnings: deprecated usage is reported as `[nero] DEPRECATION WARNING: ...` on stderr (via `Kernel#warn`, so `-W0` silences it). `Nero::Parser#parse` exposes them as `Result#warnings`.
58
+
59
+ ## Bug fixes
60
+
61
+ - `!path/git_root` / `!path/rails_root` join all segments again, as in 0.6 (`[config, app.yml]` → `<root>/config/app.yml`; the release candidates dropped all but the first), so other tags can fill in segments: `!path/rails_root [storage, !env TENANT]`. A `nil` segment (e.g. a missing `!env?`), an absolute segment, a mapping or a non-string is a parse error instead of silently resolving to the root (or crashing on a number).
62
+ - Tag arguments: a bare tag (`a: !my/tag`) passes no args (`[]`, was `[nil]`), and a quoted scalar stays a string (`!my/tag "123"` → `["123"]`, `!my/tag ""` → `[""]`; was `[123]` and `[nil]`).
63
+ - `!env/integer` parses decimal only: `08` is `8` instead of an error (`Integer("08")` reads it as octal).
64
+ - `!env` (and the coercing variants) without a variable name is a parse error instead of looking up `nil`.
65
+ - `!ref [a, c]` resolved silently to `a` during the refactor; it resolves to `a.c` again.
66
+ - Rails: `Nero.config_for(:app)` reads `Rails.root/config/app.yml` again, whatever the current directory (as 0.6 did via `config_dir`); without Rails it's `./config`. `Nero.config_dir` is the method to override.
67
+ - Rails: credentials are looked up when a `!credentials` tag resolves, so parsing works before (or without) a Rails application; a `false` credential is returned instead of reported missing; a block passed to `parse`/`config_for` runs once.
68
+
69
+ ## Developer
70
+
71
+ - Appraisal (psych 3/4 gemfiles) dropped; CI runs Ruby 3.3, 3.4, 4.0 and head.
72
+ - All GitHub Actions pinned to a commit SHA and updated.
73
+ - Specs: `sample` helper for table-driven specs (`spec/support/samples.rb`).
74
+ - `bin/console` has `reload!`.
3
75
 
4
76
  ## [0.6.0] - 2025-04-10
5
77
 
data/README.md CHANGED
@@ -13,7 +13,7 @@ development:
13
13
  secret: !env [SECRET, "dummy"]
14
14
 
15
15
  # optional env-var with coercion
16
- debug?: !env/bool? DEBUG
16
+ debug?: !env?/bool DEBUG
17
17
 
18
18
  production:
19
19
  # required env-var (not required during development)
@@ -23,21 +23,26 @@ production:
23
23
  max_threads: !env/integer [MAX_THREADS, 5]
24
24
 
25
25
  # refer to other keys
26
- min_threads: !env/integer [MIN_THREADS, !ref max_threads ]
26
+ min_threads: !env/integer [MIN_THREADS, !ref max_threads]
27
+
28
+ # build strings
29
+ database_url: !format ["postgres://%s/app", !env DB_HOST]
27
30
 
28
31
  # descriptive names
29
- asset_folder: !path/rails_root [ public/assets ]
32
+ asset_folder: !path/rails_root public/assets
30
33
 
31
- # easy to add custom tags
34
+ # Rails: durations, credentials
32
35
  cache_ttl: !duration [2, hours]
36
+ api_key: !credentials [stripe, api_key]
33
37
  ```
34
38
 
35
39
  ## Highlights
36
40
 
37
41
  * 💎 declarative YAML-tags for e.g. requiring and coercing env-vars
42
+ * 🧾 all problems reported at once, not just the first
38
43
  * 🛠️ add custom tags
39
44
  * 🛤️ `Rails.application.config_for` drop-in
40
- * ♻️ Zeitwerk-only dependency
45
+ * ♻️ no dependencies
41
46
 
42
47
  ## Installation
43
48
 
@@ -47,36 +52,21 @@ Install the gem and add to the application's Gemfile by executing:
47
52
  bundle add nero
48
53
  ```
49
54
 
50
- ## Configuration
51
-
52
- ```ruby
53
- Nero.configure do |nero|
54
- # Path that `Nero.config_for` uses to resolve Symbol or String files, e.g. `Nero.config_for(:app)`
55
- nero.config_dir = "config"
56
-
57
- # Add custom tags (also see section about custom tags)
58
- nero.add_tag("upcase") do |tag|
59
- # tag is an instance of [Nero::BaseTag](https://eval.github.io/nero/Nero/BaseTag.html).
60
- tag.args.join.upcase
61
- end
62
- end
63
- ```
64
-
65
55
  ## Usage
66
56
 
67
57
  > [!WARNING]
68
- > It's early days - the API and included tags will certainly change. Check the CHANGELOG when upgrading.
58
+ > It's early days - the API and included tags will certainly change. Check the CHANGELOG when upgrading, and [UPGRADING.md](UPGRADING.md) when coming from 0.6.
69
59
 
70
60
  ### loading a config
71
61
 
72
62
  Given the following config:
73
63
  ```yaml
74
- # config/settings.yml
64
+ # config/app.yml
75
65
  development:
76
66
  # env-var with a fallback
77
67
  secret: !env [SECRET, "dummy"]
78
- # Though the default is false, explicitly providing "false"/"off"/"n"/"no" also works.
79
- debug?: !env/bool? DEBUG
68
+ # nil when DEBUG is not set
69
+ debug?: !env?/bool DEBUG
80
70
  production:
81
71
  # fail-fast on absence of SECRET
82
72
  secret: !env SECRET
@@ -88,41 +78,56 @@ Loading this config:
88
78
 
89
79
  ```ruby
90
80
  # Loading development
91
- Nero.load_file("config/settings", root: :development)
81
+ Nero.load_file("config/app.yml", root: :development)
92
82
  # ...and no ENV-vars were provided
93
- #=> {secret: "dummy", debug?: false}
83
+ #=> {"secret" => "dummy", "debug?" => nil}
94
84
 
95
- # ...with ENV {"debug" => "true"}
96
- #=> {secret: "dummy", debug?: true}
85
+ # ...with ENV {"DEBUG" => "true"}
86
+ #=> {"secret" => "dummy", "debug?" => true}
97
87
 
98
88
  # Loading production
99
- Nero.load_file("config/settings", root: :production)
89
+ Nero.load_file("config/app.yml", root: :production)
100
90
  # ...and no ENV-vars were provided
101
- # raises error: key not found: "SECRET" (KeyError)
91
+ # raises Nero::ParseError: environment variable SECRET is not set
102
92
 
103
93
  # ...with ENV {"SECRET" => "s3cr3t", "MAX_THREADS" => "3"}
104
- #=> {secret: "s3cr3t", max_threads: 3}
94
+ #=> {"secret" => "s3cr3t", "max_threads" => 3}
105
95
  ```
106
- > [!TIP]
107
- > You can also use `Nero.config_for` (similar to [Rails.application.config_for](https://api.rubyonrails.org/classes/Rails/Application.html#method-i-config_for)).
108
- > In Rails applications this gets configured for you. For other application you might need to adjust the `config_dir`:
96
+
97
+ Nero's entry points behave like their namesakes:
98
+
99
+ | | Behaves like | Keys | Classes YAML may create |
100
+ |---|---|---|---|
101
+ | `Nero.load(yaml)`, `Nero.load_file(path)` | `YAML.load`, `YAML.load_file` | strings (`symbolize_names: true` for symbols) | `Symbol` |
102
+ | `Nero.config_for(:app, env:)` | `Rails.application.config_for` | symbols | `Symbol`, `Date`, `Time` |
103
+
104
+ Differences from `YAML.load`: aliases (anchors) are allowed, and all problems are reported at once in a `Nero::ParseError` (see `#errors`). Allow more classes with `permitted_classes:` (this replaces the default list, as in Psych). Arbitrary objects (`!ruby/object:...`) are refused by default, also in `config_for` (Rails' `config_for` uses `YAML.unsafe_load`).
105
+
109
106
  ```ruby
110
- Nero.configure do |config|
111
- config.config_dir = "config"
112
- end
107
+ # config/app.yml, relative to the current directory (in Rails: Rails.root/config)
108
+ Nero.config_for(:app, env: :production)
109
+ #=> {secret: "s3cr3t", max_threads: 3}
113
110
 
114
- Nero.config_for(:settings, env: Rails.env)
111
+ # Pass the env-vars to use (default: ENV), e.g. in specs
112
+ Nero.load_file("config/app.yml", root: :production, environ: {"SECRET" => "s3cr3t"})
113
+ #=> {"secret" => "s3cr3t", "max_threads" => 5}
114
+
115
+ # Without raising: a Result with value, errors and warnings
116
+ result = Nero::Parser.new(root: :production).parse_file("config/app.yml")
117
+ result.ok? #=> false
118
+ result.errors.map(&:message) #=> ["environment variable SECRET is not set"]
119
+ result.value! # raises Nero::ParseError
115
120
  ```
116
121
 
122
+ Deprecated usage (e.g. `!ref [a, b]`) still works and prints a warning on stderr, like `[nero] DEPRECATION WARNING: ...`. `Nero::Parser` doesn't print: see `Result#warnings`.
123
+
117
124
  [API Documentation](https://eval.github.io/nero/).
118
125
 
119
126
  ### built-in tags
120
127
 
121
- The following tags are provided:
122
128
  - `!env KEY`, `!env? KEY`
123
129
  Resp. to fetch or get a value from `ENV`:
124
130
  ```yaml
125
- ---
126
131
  # required
127
132
  secret: !env SECRET
128
133
  # optional, with fallback:
@@ -130,186 +135,245 @@ The following tags are provided:
130
135
  # ...or nil
131
136
  secret: !env? SECRET
132
137
  ```
133
- - to coerce env-values:
134
- - `env/integer`, `env/integer?`, `env/float`, `env/float?`:
138
+ - `!env/<type> KEY`, `!env?/<type> KEY`
139
+ Coerce env-values: `env/<type>` is required, `env?/<type>` optional (`nil` when not provided). The types are `integer` (or `int`), `float`, `bool` (or `boolean`), `path` (a [Pathname](https://rubyapi.org/3.4/o/pathname)), `ip` (an [IPAddr](https://rubyapi.org/3.4/o/ipaddr), see `!ip`) and `list`:
140
+ ```yaml
141
+ port: !env/integer [PORT, 3000]
142
+ threads: !env?/integer THREADS # nil when not provided
143
+ threshold: !env/float CUTOFF
144
+ log_dir: !env/path [LOG_DIR, log]
145
+ admin_ip: !env?/ip ADMIN_IP
146
+ ```
147
+ - lists split on commas and strip whitespace (`a.com, b.com` → `["a.com", "b.com"]`, empty → `[]`). The fallback can be a string or a sequence:
135
148
  ```yaml
136
- port: !env/integer [PORT, 3000]
137
- threads: !env/integer? THREADS # nil when not provided
138
- threshold: !env/float CUTOFF
149
+ allowed_hosts: !env/list [ALLOWED_HOSTS, [localhost, 127.0.0.1]]
150
+ cors_origins: !env?/list CORS_ORIGINS
139
151
  ```
140
- - `env/bool`, `env/bool?`:
152
+ - bools accept `1/y/yes/true/on` and `0/n/no/false/off` (case-insensitive); anything else is an error:
141
153
  ```yaml
142
- # required (valid values 'y(es)'/'n(o)', 'true'/'false', 'on'/'off')
154
+ # required
143
155
  over18: !env/bool OVER18
144
156
  # optional, with fallback:
145
157
  secure: !env/bool [SECURE, true]
146
- # ...or false:
147
- debug?: !env/bool? DEBUG
158
+ # ...or nil:
159
+ debug?: !env?/bool DEBUG
148
160
  ```
149
- > [!TIP]
150
- > Make all env-var's optional by providing `ENV["NERO_ENV_ALL_OPTIONAL"]`, e.g.
151
- ```shell
152
- $ env NERO_ENV_ALL_OPTIONAL=1 SECRET_KEY_BASE_DUMMY=1 rails asset:precompile
153
- ```
154
- - `!path`
155
- Create a [Pathname](https://rubyapi.org/3.4/o/pathname):
156
- ```yaml
157
- config: !path config
158
- # combining tags:
159
- asset_folder: !path
160
- - !env PROJECT_ROOT
161
- - /public/assets
162
- ```
163
- - `!path/git_root`, `!path/rails_root`
164
- Create a Pathname relative to some root-path.
165
- The root-path is expected to be an existing ancestor folder of the yaml-config being parsed.
166
- It's found by traversing up and checking for the presence of specific files/folders, e.g. '.git' (`!path/git_root`) or 'config.ru' (`!path/rails_root`).
167
- While the root-path needs to exist, the resulting Pathname doesn't need to.
161
+ - The names `env/integer?` etc. (with the `?` at the end) still work, with a deprecation warning, until 0.8.
162
+
163
+ > [!TIP]
164
+ > Set `NERO_ALL_OPTIONAL` to make every env var (and, with Rails, every `!credentials` key) optional: missing values become their fallback or `nil` instead of an error. For tasks that boot the app without needing its config:
165
+ > ```shell
166
+ > $ NERO_ALL_OPTIONAL=1 SECRET_KEY_BASE_DUMMY=1 rails assets:precompile
167
+ > $ NERO_ALL_OPTIONAL=1 rails credentials:edit --environment production
168
+ > ```
169
+ > Or per call: `Nero.load(yaml, all_optional: true)`. The old name `NERO_ENV_ALL_OPTIONAL` still works, with a deprecation warning, until 0.8.
170
+ - `!path/git_root`
171
+ Create a [Pathname](https://rubyapi.org/3.4/o/pathname) relative to the root of the project: the nearest ancestor folder of the yaml-config that contains `.git`.
172
+ While the root needs to exist, the resulting Pathname doesn't need to.
168
173
  ```yaml
169
174
  project_root: !path/git_root
170
- config_folder: !path/rails_root [ config ]
171
- ```
172
- - `!uri`
173
- Create a [URI](https://rubyapi.org/3.4/o/uri):
174
- ```yaml
175
- smtp_url: !uri
176
- - smtps://
177
- - !env SMTP_CREDS
178
- - @smtp.gmail.com
175
+ schema: !path/git_root db/schema.rb
176
+ # segments are joined, so other tags can provide them:
177
+ uploads: !path/git_root [storage, !env [TENANT, default]]
179
178
  ```
180
- - `!str/format`
181
- Using Ruby's [format specifications](https://docs.ruby-lang.org/en/master/format_specifications_rdoc.html):
179
+ Segments are relative to the root: a missing (`nil`) or absolute segment is an error.
180
+ With Rails there's also `!path/rails_root` (see [Rails](#rails)).
181
+ - `!format` (or `!str/format`)
182
+ Using Ruby's [format specifications](https://docs.ruby-lang.org/en/master/language/format_specifications_rdoc.html):
182
183
  ```yaml
183
- smtp_url: !str/format
184
+ # template + positional arguments
185
+ smtp_url: !format
184
186
  - smtps://%s:%s@smtp.gmail.com
185
187
  - !env SMTP_USER
186
188
  - !env SMTP_PASS
187
-
188
- # pass it a map (including a key 'fmt') to use references
189
- smtp_url: !str/format
190
- fmt: smtps://%<user>s:%<pass>s@smtp.gmail.com
191
- user: !env SMTP_USER
192
- pass: !env SMTP_PASS
189
+
190
+ # template + named arguments
191
+ smtp_url: !format
192
+ - smtps://%<user>s:%<pass>s@smtp.gmail.com
193
+ - user: !env SMTP_USER
194
+ pass: !env SMTP_PASS
195
+
196
+ # as oneliner
197
+ greeting: !format [Hello %<demonyms>s on %<planet>s!, planet: Earth, demonyms: people]
193
198
  ```
199
+ - `!ip`
200
+ An [IPAddr](https://rubyapi.org/3.4/o/ipaddr) from an address or CIDR range (IPv4 or IPv6):
201
+ ```yaml
202
+ admin: !ip 10.0.0.1
203
+ office: !ip 192.168.0.0/24
204
+ # a sequence of one, to nest a tag:
205
+ admin_ip: !ip [!env [ADMIN_IP, 127.0.0.1]]
206
+ # for several: a list with one !ip per item
207
+ trusted_proxies:
208
+ - !ip 173.245.48.0/20
209
+ - !ip 2400:cb00::/32
210
+ ```
211
+ Ranges answer `include?`: `config["office"].include?(request.remote_ip)`.
194
212
  - `!ref`
195
213
  Include values from elsewhere:
196
214
  ```yaml
197
215
  # simple
198
- min_threads: !env/integer [MIN_THREADS, !ref [max_threads]]
216
+ min_threads: !env/integer [MIN_THREADS, !ref max_threads]
199
217
  max_threads: 5
200
-
218
+
201
219
  # oauth_callback -refs-> base.url -refs-> base.host
202
220
  base:
203
- host: !env [HOST]
204
- url: !str/format ['https://%s', !ref[base, host]]
205
- oauth_callback: !str/format
221
+ host: !env HOST
222
+ url: !format [https://%s, !ref base.host]
223
+ oauth_callback: !format
206
224
  - '%s/oauth/callback'
207
- - !ref[base, url]
208
-
209
- # refs are resolved within the tree of the selected root.
210
- # The following config won't work when doing `Nero.load_config(:app, root: :prod)`
225
+ - !ref base.url
226
+ ```
227
+ Paths are relative to the selected root, and must exist (`unknown ref ...` otherwise). So with `root: :prod` this doesn't work:
228
+ ```yaml
211
229
  dev:
212
230
  max_threads: 5
213
231
  prod:
214
- max_threads: !env[MAX_THREADS, !ref[dev, max_threads]]
232
+ max_threads: !env/integer [MAX_THREADS, !ref dev.max_threads]
233
+ ```
234
+ Use an anchor instead (`max_threads: &max_threads 5` and `*max_threads`).
235
+ The form `!ref [base, url]` still works, with a deprecation warning, until 0.8.
236
+
237
+ ### Rails
238
+
239
+ In a Rails app (when Nero is required after Rails, as Bundler does) `nero/rails` is loaded. Elsewhere: `require "nero/rails"`. This makes `Nero.config_for` look in `Rails.root/config` with `env:` defaulting to `Rails.env`:
240
+
241
+ ```ruby
242
+ # config/application.rb
243
+ config.x.app = Nero.config_for(:app)
244
+ ```
245
+
246
+ ...and adds these tags:
247
+
248
+ - `!credentials`
249
+ A value from `Rails.application.credentials`. For nested keys, use a sequence:
250
+ ```yaml
251
+ secret_key_base: !credentials secret_key_base
252
+ stripe_key: !credentials [stripe, api_key]
253
+ ```
254
+ A missing credential is an error (`nil` with `NERO_ALL_OPTIONAL`).
255
+ - `!path/rails_root`
256
+ Like `!path/git_root`, with the folder containing `config.ru` as root:
257
+ ```yaml
258
+ asset_folder: !path/rails_root public/assets
259
+ ```
260
+ - `!duration`
261
+ An `ActiveSupport::Duration` from an amount and a unit (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months` or `years`):
262
+ ```yaml
263
+ cache_ttl: !duration [2, hours]
264
+ session_timeout: !duration [!env/integer [SESSION_MINUTES, 30], minutes]
265
+ ```
266
+ - `!str/inquirer`
267
+ An `ActiveSupport::StringInquirer`, like `Rails.env`:
268
+ ```yaml
269
+ stage: !str/inquirer [!env [STAGE, beta]]
270
+ # config[:stage].beta? #=> true
215
271
  ```
216
- NOTE future version should raise properly over ref-ing a non-existing path.
217
272
 
218
273
  ### custom tags
219
274
 
220
- There's three ways to create your own tags.
275
+ Pass a block to `Nero.load`, `Nero.load_file`, `Nero.config_for` or `Nero::Parser.new` and register tags with `add_tag(name, tag)`. Built-in tags with the same name are replaced.
221
276
 
222
- For all these methods it's helpful to see the API-docs for [Nero::BaseTag](https://eval.github.io/nero/Nero/BaseTag.html).
277
+ A tag is anything that responds to `resolve(args, context:)`:
278
+ - `args` is what follows the tag in YAML: an Array for a scalar or sequence, a Hash for a mapping. Nested tags (`!env` etc.) are already resolved.
279
+ - `context` gives access to `environ` (the env-vars), `dir` (the folder of the yaml-config) and `add_error(message)`.
280
+
281
+ There's three ways to create your own tags.
223
282
 
224
- 1. **a proc**
283
+ 1. **a lambda**
225
284
  ```ruby
226
- Nero.configure do |nero|
227
- nero.add_tag("upcase") do |tag|
228
- # `tag` is a `Nero::BaseTag`.
285
+ Nero.load_file("config/app.yml") do |nero|
286
+ nero.add_tag("upcase", ->(args, context:) {
229
287
  # In YAML args are provided as scalar, seq or map:
230
- # ---
231
- # k: !upcase bar
232
- # ---
233
- # k: !upcase [bar] # equivalent to:
234
- # k: !upcase
235
- # - bar
236
- # ---
237
- # k: !upcase
238
- # bar: baz
239
- #
240
- # Find these args via `tag.args` (Array or Hash):
241
- case tag.args
242
- when Hash
243
- tag.args.each_with_object({}) {|(k,v), acc| acc[k] = v.upcase }
244
- else
245
- tag.args.map(&:upcase)
288
+ # k: !upcase bar # args: ["bar"] => "BAR"
289
+ # k: !upcase [foo, bar] # args: ["foo", "bar"] => "FOO BAR"
290
+ # k: !upcase # args: {"bar" => "baz"} => {"bar" => "BAZ"}
291
+ # bar: baz # (keys are strings, or symbols with config_for)
292
+ case args
293
+ when Hash then args.transform_values(&:upcase)
294
+ else args.join(" ").upcase
246
295
  end
247
-
248
- # NOTE though a tag might just need one argument (ie scalar),
249
- # it's helpful to accept a seq as it allows for chaining:
250
- # a: !my/inc 4 # scalar suffices
251
- # ...but when chaining, it needs to be a seq:
252
- # a: !my/inc [ !my/square 2 ]
253
- end
296
+ })
254
297
  end
255
298
  ```
256
- Blocks are passed instances of [Nero::BaseTag](https://eval.github.io/nero/Nero/BaseTag.html).
257
- 1. **re-use existing tag-class**
258
- You can add an existing tag under a better fitting name this way.
259
- Also: some tag-classes have options that allow for simple customizations (like `coerce` below):
299
+ Though a tag might just need one argument (ie scalar), it's helpful to accept a seq as it allows for nesting:
300
+ ```yaml
301
+ a: !upcase foo # scalar suffices
302
+ b: !upcase [!env [FOO, foo]] # ...but nesting a tag needs a seq
303
+ ```
304
+ 1. **re-use an existing tag-class**
305
+ Add an existing tag under a better fitting name, or use its options for simple customizations:
260
306
  ```ruby
261
- Nero.configure do |nero|
262
- nero.add_tag("env/upcase", klass: Nero::EnvTag[coerce: :upcase])
263
-
307
+ Nero.load_file("config/app.yml") do |nero|
264
308
  # Alias for path/git_root:
265
- nero.add_tag("path/project_root", klass: Nero::PathRootTag[containing: '.git'])
309
+ nero.add_tag("path/project_root", Nero::RootPathTag.new(containing: ".git"))
310
+ # env-tag with custom coercion:
311
+ nero.add_tag("env/upcase", Nero::EnvTag.new(coerce: ->(value) { value.upcase }))
312
+ nero.add_tag("env?/upcase", Nero::EnvTag.new(coerce: ->(value) { value.upcase }, optional: true))
266
313
  end
267
314
  ```
268
315
  1. **custom class**
269
316
  ```ruby
270
317
  class RotTag < Nero::BaseTag
271
- # Configure:
272
- # ```
273
- # config.add_tag("rot/12", klass: RotTag[n: 12])
274
- # config.add_tag("rot/10", klass: RotTag[n: 10]) do |secret|
275
- # "#{secret} (try breaking this!)"
276
- # end
277
- # ```
278
- #
279
- # Usage in YAML:
280
- # ```
281
- # secret: !rot/12 some message
282
- # very_secret: !rot/10 [ !env [ MSG, some message ] ]
283
- # ```
284
- # => {secret: "EAyq yqEEmsq", very_secret: "Cywo woCCkqo (try breaking this!)"}
285
-
286
- # By overriding `init_options` we can restrict/require options,
287
- # provide default values and do any other setup.
288
- # By default an option is available via `options[:foo]`.
289
- def init_options(n: 10)
290
- super # no specific assignments, so available via `options[:n]`.
291
- end
318
+ CHARS = [*"a".."z", *"A".."Z", *"0".."9"].join
292
319
 
293
- def chars
294
- @chars ||= (('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a)
320
+ def initialize(n)
321
+ @n = n
295
322
  end
296
323
 
297
- def resolve(**) # currently no keywords are passed, but `**` allows for future ones.
298
- # Here we actually do the work: get the args, rotate strings and delegate to the block.
299
- # `args` are the resolved nested args (so e.g. `!env MSG` is already resolved).
300
- # `config` is the tag's config, and contains e.g. the block.
301
- block = config.fetch(:block, :itself.to_proc)
324
+ # Usage in YAML:
325
+ # secret: !rot/12 some message
326
+ # very_secret: !rot/10 [!env [MSG, some message]]
327
+ def resolve(args, context:)
328
+ unless args.is_a?(Array) && args.all?(String)
329
+ # Report problems instead of raising: they end up in Nero::ParseError with all other problems.
330
+ context.add_error("!rot expects one or more strings, got #{args.inspect}")
331
+ return
332
+ end
333
+
302
334
  # String#tr replaces any character from the first collection with the same position in the other:
303
- args.join.tr(chars.join, chars.rotate(options[:n]).join).then(&block)
335
+ args.join.tr(CHARS, CHARS.chars.rotate(@n).join)
304
336
  end
305
337
  end
338
+
339
+ Nero.load_file("config/app.yml") do |nero|
340
+ nero.add_tag("rot/12", RotTag.new(12))
341
+ nero.add_tag("rot/10", RotTag.new(10))
342
+ end
343
+ #=> {"secret" => "EAyq yqEEmsq", "very_secret" => "Cywo woCCkqo"}
306
344
  ```
307
345
 
308
346
  ## Development
309
347
 
310
- After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
348
+ ```bash
349
+ # Setup
350
+ bin/setup # Make sure it exits with code 0
351
+
352
+ # Run tests
353
+ rake
354
+ ```
311
355
 
312
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
356
+ Using [mise](https://mise.jdx.dev/) for env-vars is recommended.
357
+
358
+ ### Releasing
359
+
360
+ 1. Update `lib/nero/version.rb`
361
+ ```
362
+ bin/rake 'gem:write_version[0.7.0]'
363
+ # commit&push
364
+ # check CI
365
+ ```
366
+ 1. Tag
367
+ ```
368
+ gem_push=no bin/rake release
369
+ ```
370
+ 1. Release workflow from GitHub Actions...
371
+ - ...publishes to RubyGems (with Sigstore attestation)
372
+ - ...creates git GitHub release after successful publish
373
+ 1. Update `version.rb` for next dev-cycle
374
+ ```
375
+ bin/rake 'gem:write_version[0.8.0.dev]'
376
+ ```
313
377
 
314
378
  ## Contributing
315
379