nero 0.7.0.rc2 → 0.7.0.rc4

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: 69db9ab0dfd43a40d12a05bd3eb311d12a292a4ba7f1ce0c9f965e908344d659
4
- data.tar.gz: 6c29320c5e9f8deafc4c3e207554f59df3e2a97240b73bcc3debefca0a6e3d04
3
+ metadata.gz: 69862dbbf75cc8abdb008ad761255fed5333c68d431a5252fcf6481436ad7698
4
+ data.tar.gz: 9ee9b59ea86c3f098ac233f7c972e75e0614f8f74386ae3b927031787d88b38a
5
5
  SHA512:
6
- metadata.gz: 5351b2b97b1d49b3a405b5f829d0f716e190a9d9439dd5d54eb8ac673b11efaed1665e352a8973de4a80cde786fda5e0061646d63beafe2626f4fd95d25bf7df
7
- data.tar.gz: 3a296f997e83ffd96a508553a638b74abbb0adef2e6487904a4c1be64809f2d5e62cfd7bc98ab0b1ee6e0092cf6888a01359209d540632325542e970102e11f3
6
+ metadata.gz: 5a0fd75b3a9025922645327af44654e9b76a83eef0b16212e4bd8591ff14b8296be358dcd332d057985a2f9b29b3171a69d562a96cb62402d08444f21cb3537b
7
+ data.tar.gz: ccbf523a3ba306df92a73b5f396f34cd1f1003802ef0ea026dbf1f0ca9863d7f52e6f55cb321c02662ca930d4fd92fb1afe4820b4e42b7f18738dd7ea7e03d1c
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,10 +1,18 @@
1
+ Changes can be:
2
+
3
+ * ✨ Features
4
+ * ⚠️ Breaking
5
+ * 🐛 Bug Fixes
6
+ * 🛠️ Developer
7
+ * 🛡️ Security
8
+
1
9
  ## [Unreleased]
2
10
 
3
- Total refactor and so quite some breaking changes.
11
+ Total refactor and so quite some breaking changes. See [UPGRADING.md](UPGRADING.md) for a step-by-step guide from 0.6.
4
12
 
5
13
  ## Breaking Changes
6
14
 
7
- - Nero.load / Nero.load_file removed — replaced by Nero.parse and Nero.parse_file. These return values directly (or raise Nero::ParseError).
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.
8
16
  - Nero.configure / Nero.configuration removed — custom tags are now registered via a block passed to parse/parse_file/config_for:
9
17
  ```ruby
10
18
  # Before
@@ -16,15 +24,54 @@ Total refactor and so quite some breaking changes.
16
24
  ```
17
25
  - `Nero::Config` removed — results are plain Hashes (string keys) instead of a Config subclass with DigExt/dig!.
18
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.
19
- - !ref syntax changed — from sequence-based !ref [base, url] to dot-notation !ref base.url.
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.
20
28
  - root: option replaces root:/env: and uses string keys (e.g. root: :development matches the string key "development").
21
- - Keys are strings — previously keys were symbolized; now they stay as strings.
29
+ - Keys: `Nero.load`/`load_file` give string keys (`symbolize_names: true` for symbols), `Nero.config_for` gives symbol keys.
22
30
  - !uri and !path tags removed — !uri is gone entirely; !path is no longer a built-in.
23
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.
24
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].
25
35
  - load_config removed (was already deprecated).
26
36
  - Nero::Util removed — deep_symbolize_keys and deep_transform_values are no longer needed.
27
- - NERO_ENV_ALL_OPTIONAL env var no longer supported.
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!`.
28
75
 
29
76
  ## [0.6.0] - 2025-04-10
30
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,18 +23,23 @@ 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
45
  * ♻️ no dependencies
@@ -47,20 +52,10 @@ 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
- parser = Nero::Parser.new do |config|
54
- config.add_tag("str/upcase", ->(args, **) { args.join.upcase })
55
- end
56
- parser.parse("hello: !str/upcase world")
57
- # => #<Nero::Result:0x00000001239f8de0 @errors=[], @value={"hello" => "WORLD"}>
58
- ```
59
-
60
55
  ## Usage
61
56
 
62
57
  > [!WARNING]
63
- > 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.
64
59
 
65
60
  ### loading a config
66
61
 
@@ -70,8 +65,8 @@ Given the following config:
70
65
  development:
71
66
  # env-var with a fallback
72
67
  secret: !env [SECRET, "dummy"]
73
- # Though the default is false, explicitly providing "false"/"off"/"n"/"no" also works.
74
- debug?: !env/bool? DEBUG
68
+ # nil when DEBUG is not set
69
+ debug?: !env?/bool DEBUG
75
70
  production:
76
71
  # fail-fast on absence of SECRET
77
72
  secret: !env SECRET
@@ -83,37 +78,56 @@ Loading this config:
83
78
 
84
79
  ```ruby
85
80
  # Loading development
86
- Nero.parse_file("config/app.yml", root: :development)
81
+ Nero.load_file("config/app.yml", root: :development)
87
82
  # ...and no ENV-vars were provided
88
- #=> {secret: "dummy", debug?: false}
83
+ #=> {"secret" => "dummy", "debug?" => nil}
89
84
 
90
- # ...with ENV {"debug" => "true"}
91
- #=> {secret: "dummy", debug?: true}
85
+ # ...with ENV {"DEBUG" => "true"}
86
+ #=> {"secret" => "dummy", "debug?" => true}
92
87
 
93
88
  # Loading production
94
- Nero.parse_file("config/app.yml", root: :production)
89
+ Nero.load_file("config/app.yml", root: :production)
95
90
  # ...and no ENV-vars were provided
96
- # raises error: key not found: "SECRET" (KeyError)
91
+ # raises Nero::ParseError: environment variable SECRET is not set
97
92
 
98
93
  # ...with ENV {"SECRET" => "s3cr3t", "MAX_THREADS" => "3"}
99
- #=> {secret: "s3cr3t", max_threads: 3}
94
+ #=> {"secret" => "s3cr3t", "max_threads" => 3}
100
95
  ```
101
- > [!TIP]
102
- > You can also use `Nero.config_for(:app)` (similar to [Rails.application.config_for](https://api.rubyonrails.org/classes/Rails/Application.html#method-i-config_for)).
103
- > 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
+
104
106
  ```ruby
105
- Nero.config_for(:settings, env: Rails.env)
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}
110
+
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
106
120
  ```
107
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
+
108
124
  [API Documentation](https://eval.github.io/nero/).
109
125
 
110
126
  ### built-in tags
111
127
 
112
- The following tags are provided:
113
128
  - `!env KEY`, `!env? KEY`
114
129
  Resp. to fetch or get a value from `ENV`:
115
130
  ```yaml
116
- ---
117
131
  # required
118
132
  secret: !env SECRET
119
133
  # optional, with fallback:
@@ -121,164 +135,212 @@ The following tags are provided:
121
135
  # ...or nil
122
136
  secret: !env? SECRET
123
137
  ```
124
- - to coerce env-values:
125
- - `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:
126
148
  ```yaml
127
- port: !env/integer [PORT, 3000]
128
- threads: !env/integer? THREADS # nil when not provided
129
- threshold: !env/float CUTOFF
149
+ allowed_hosts: !env/list [ALLOWED_HOSTS, [localhost, 127.0.0.1]]
150
+ cors_origins: !env?/list CORS_ORIGINS
130
151
  ```
131
- - `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:
132
153
  ```yaml
133
- # required (valid values 'y(es)'/'n(o)', 'true'/'false', 'on'/'off')
154
+ # required
134
155
  over18: !env/bool OVER18
135
156
  # optional, with fallback:
136
157
  secure: !env/bool [SECURE, true]
137
- # ...or false:
138
- debug?: !env/bool? DEBUG
158
+ # ...or nil:
159
+ debug?: !env?/bool DEBUG
139
160
  ```
140
- > [!TIP]
141
- > Make all env-var's optional by providing `ENV["NERO_ENV_ALL_OPTIONAL"]`, e.g.
142
- ```shell
143
- $ env NERO_ENV_ALL_OPTIONAL=1 SECRET_KEY_BASE_DUMMY=1 rails asset:precompile
144
- ```
145
- - `!path`
146
- Create a [Pathname](https://rubyapi.org/3.4/o/pathname):
147
- ```yaml
148
- config: !path config
149
- # combining tags:
150
- asset_folder: !path
151
- - !env PROJECT_ROOT
152
- - /public/assets
153
- ```
154
- - `!path/git_root`, `!path/rails_root`
155
- Create a Pathname relative to some root-path.
156
- The root-path is expected to be an existing ancestor folder of the yaml-config being parsed.
157
- 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`).
158
- 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.
159
173
  ```yaml
160
174
  project_root: !path/git_root
161
- config_folder: !path/rails_root [ config ]
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]]
162
178
  ```
163
- - `!uri`
164
- Create a [URI](https://rubyapi.org/3.4/o/uri):
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):
165
183
  ```yaml
166
- smtp_url: !uri
167
- - smtps://
168
- - !env SMTP_CREDS
169
- - @smtp.gmail.com
170
- ```
171
- - `!str/format`
172
- Using Ruby's [format specifications](https://docs.ruby-lang.org/en/master/format_specifications_rdoc.html):
173
- ```yaml
174
- smtp_url: !str/format
184
+ # template + positional arguments
185
+ smtp_url: !format
175
186
  - smtps://%s:%s@smtp.gmail.com
176
187
  - !env SMTP_USER
177
188
  - !env SMTP_PASS
178
-
179
- # pass it a map (including a key 'fmt') to use references
180
- smtp_url: !str/format
189
+
190
+ # template + named arguments
191
+ smtp_url: !format
181
192
  - smtps://%<user>s:%<pass>s@smtp.gmail.com
182
193
  - user: !env SMTP_USER
183
194
  pass: !env SMTP_PASS
195
+
196
+ # as oneliner
197
+ greeting: !format [Hello %<demonyms>s on %<planet>s!, planet: Earth, demonyms: people]
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
184
210
  ```
211
+ Ranges answer `include?`: `config["office"].include?(request.remote_ip)`.
185
212
  - `!ref`
186
213
  Include values from elsewhere:
187
214
  ```yaml
188
215
  # simple
189
- min_threads: !env/integer [MIN_THREADS, !ref [max_threads]]
216
+ min_threads: !env/integer [MIN_THREADS, !ref max_threads]
190
217
  max_threads: 5
191
-
218
+
192
219
  # oauth_callback -refs-> base.url -refs-> base.host
193
220
  base:
194
- host: !env [HOST]
195
- url: !str/format ['https://%s', !ref[base, host]]
196
- oauth_callback: !str/format
221
+ host: !env HOST
222
+ url: !format [https://%s, !ref base.host]
223
+ oauth_callback: !format
197
224
  - '%s/oauth/callback'
198
- - !ref[base, url]
199
-
200
- # refs are resolved within the tree of the selected root.
201
- # The following config won't work when doing `Nero.load_file("config/app.yml", 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
202
229
  dev:
203
230
  max_threads: 5
204
231
  prod:
205
- 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
206
271
  ```
207
- NOTE future version should raise properly over ref-ing a non-existing path.
208
272
 
209
273
  ### custom tags
210
274
 
211
- 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.
212
276
 
213
- 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)`.
214
280
 
215
- 1. **a proc**
281
+ There's three ways to create your own tags.
282
+
283
+ 1. **a lambda**
216
284
  ```ruby
217
- Nero.configure do |nero|
218
- nero.add_tag("upcase") do |args, context:|
285
+ Nero.load_file("config/app.yml") do |nero|
286
+ nero.add_tag("upcase", ->(args, context:) {
219
287
  # In YAML args are provided as scalar, seq or map:
220
- # ---
221
- # k: !upcase bar
222
- # ---
223
- # k: !upcase [bar] # equivalent to:
224
- # k: !upcase
225
- # - bar
226
- # ---
227
- # k: !upcase
228
- # bar: baz
229
- #
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)
230
292
  case args
231
- when Hash
232
- args.each_with_object({}) {|(k,v), acc| acc[k] = v.upcase }
233
- else
234
- args.map(&:upcase)
293
+ when Hash then args.transform_values(&:upcase)
294
+ else args.join(" ").upcase
235
295
  end
236
-
237
- # NOTE though a tag might just need one argument (ie scalar),
238
- # it's helpful to accept a seq as it allows for chaining:
239
- # a: !my/inc 4 # scalar suffices
240
- # ...but when chaining, it needs to be a seq:
241
- # a: !my/inc [ !my/square 2 ]
242
- end
296
+ })
243
297
  end
244
298
  ```
245
- Blocks are passed instances of [Nero::BaseTag](https://eval.github.io/nero/Nero/BaseTag.html).
246
- 1. **re-use existing tag-class**
247
- You can add an existing tag under a better fitting name this way.
248
- 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:
249
306
  ```ruby
250
- Nero.configure do |nero|
307
+ Nero.load_file("config/app.yml") do |nero|
251
308
  # Alias for path/git_root:
252
- nero.add_tag("path/project_root", Nero::RootPathTag.new(".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))
253
313
  end
254
314
  ```
255
315
  1. **custom class**
256
316
  ```ruby
257
317
  class RotTag < Nero::BaseTag
258
- # Configure:
259
- # ```
260
- # config.add_tag("rot/12", RotTag.new(12))
261
- # config.add_tag("rot/10", RotTag.new(10))
262
- # ```
263
- #
264
- # Usage in YAML:
265
- # ```
266
- # secret: !rot/12 some message
267
- # very_secret: !rot/10 [ !env [ MSG, some message ] ]
268
- # ```
269
- # => {secret: "EAyq yqEEmsq", very_secret: "Cywo woCCkqo)"}
270
-
271
- def chars
272
- @chars ||= (('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a)
318
+ CHARS = [*"a".."z", *"A".."Z", *"0".."9"].join
319
+
320
+ def initialize(n)
321
+ @n = n
273
322
  end
274
323
 
324
+ # Usage in YAML:
325
+ # secret: !rot/12 some message
326
+ # very_secret: !rot/10 [!env [MSG, some message]]
275
327
  def resolve(args, context:)
276
- # Here we actually do the work: get the args, rotate strings and delegate to the block.
277
- # `args` are the resolved nested args (so e.g. `!env MSG` is already resolved).
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
+
278
334
  # String#tr replaces any character from the first collection with the same position in the other:
279
- args.join.tr(chars.join, chars.rotate(@n).join)
335
+ args.join.tr(CHARS, CHARS.chars.rotate(@n).join)
280
336
  end
281
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"}
282
344
  ```
283
345
 
284
346
  ## Development
@@ -295,9 +357,9 @@ Using [mise](https://mise.jdx.dev/) for env-vars is recommended.
295
357
 
296
358
  ### Releasing
297
359
 
298
- 1. Update `lib/bonchi/version.rb`
360
+ 1. Update `lib/nero/version.rb`
299
361
  ```
300
- bin/rake 'gem:write_version[0.5.0]'
362
+ bin/rake 'gem:write_version[0.7.0]'
301
363
  # commit&push
302
364
  # check CI
303
365
  ```
@@ -310,7 +372,7 @@ Using [mise](https://mise.jdx.dev/) for env-vars is recommended.
310
372
  - ...creates git GitHub release after successful publish
311
373
  1. Update `version.rb` for next dev-cycle
312
374
  ```
313
- bin/rake 'gem:write_version[0.6.0.dev]'
375
+ bin/rake 'gem:write_version[0.8.0.dev]'
314
376
  ```
315
377
 
316
378
  ## Contributing