initable 0.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 11652b09ebedba190e0b35394028990c76e9102ab9f0a35f16d48af094cfeb74
4
+ data.tar.gz: a92c36ccaa4ee2b6ee7cb8598017fb8a10c92769255196bf301df8594b6ec812
5
+ SHA512:
6
+ metadata.gz: fce4f982b787297b4d392fab52a64fd77684b74516007f403badf86abaeea65cae9129c48f02b343ac3d57b0783731b36ff07ddc46762252eac9dea259e142ca
7
+ data.tar.gz: 17ab62fe13848134324f536a8d4b0b867623d37c538aec81aa724b5ff7b9c51cb2137270681948895f72baf949ff33a5ef02a5fc342ce7691e70c388fb5d294f
checksums.yaml.gz.sig ADDED
Binary file
data/LICENSE.adoc ADDED
@@ -0,0 +1,134 @@
1
+ = Hippocratic License
2
+
3
+ Version: 2.1.0.
4
+
5
+ Purpose. The purpose of this License is for the Licensor named above to
6
+ permit the Licensee (as defined below) broad permission, if consistent
7
+ with Human Rights Laws and Human Rights Principles (as each is defined
8
+ below), to use and work with the Software (as defined below) within the
9
+ full scope of Licensor’s copyright and patent rights, if any, in the
10
+ Software, while ensuring attribution and protecting the Licensor from
11
+ liability.
12
+
13
+ Permission and Conditions. The Licensor grants permission by this
14
+ license ("License"), free of charge, to the extent of Licensor’s
15
+ rights under applicable copyright and patent law, to any person or
16
+ entity (the "Licensee") obtaining a copy of this software and
17
+ associated documentation files (the "Software"), to do everything with
18
+ the Software that would otherwise infringe (i) the Licensor’s copyright
19
+ in the Software or (ii) any patent claims to the Software that the
20
+ Licensor can license or becomes able to license, subject to all of the
21
+ following terms and conditions:
22
+
23
+ * Acceptance. This License is automatically offered to every person and
24
+ entity subject to its terms and conditions. Licensee accepts this
25
+ License and agrees to its terms and conditions by taking any action with
26
+ the Software that, absent this License, would infringe any intellectual
27
+ property right held by Licensor.
28
+ * Notice. Licensee must ensure that everyone who gets a copy of any part
29
+ of this Software from Licensee, with or without changes, also receives
30
+ the License and the above copyright notice (and if included by the
31
+ Licensor, patent, trademark and attribution notice). Licensee must cause
32
+ any modified versions of the Software to carry prominent notices stating
33
+ that Licensee changed the Software. For clarity, although Licensee is
34
+ free to create modifications of the Software and distribute only the
35
+ modified portion created by Licensee with additional or different terms,
36
+ the portion of the Software not modified must be distributed pursuant to
37
+ this License. If anyone notifies Licensee in writing that Licensee has
38
+ not complied with this Notice section, Licensee can keep this License by
39
+ taking all practical steps to comply within 30 days after the notice. If
40
+ Licensee does not do so, Licensee’s License (and all rights licensed
41
+ hereunder) shall end immediately.
42
+ * Compliance with Human Rights Principles and Human Rights Laws.
43
+ [arabic]
44
+ . Human Rights Principles.
45
+ [loweralpha]
46
+ .. Licensee is advised to consult the articles of the United Nations
47
+ Universal Declaration of Human Rights and the United Nations Global
48
+ Compact that define recognized principles of international human rights
49
+ (the "Human Rights Principles"). Licensee shall use the Software in a
50
+ manner consistent with Human Rights Principles.
51
+ .. Unless the Licensor and Licensee agree otherwise, any dispute,
52
+ controversy, or claim arising out of or relating to (i) Section 1(a)
53
+ regarding Human Rights Principles, including the breach of Section 1(a),
54
+ termination of this License for breach of the Human Rights Principles,
55
+ or invalidity of Section 1(a) or (ii) a determination of whether any Law
56
+ is consistent or in conflict with Human Rights Principles pursuant to
57
+ Section 2, below, shall be settled by arbitration in accordance with the
58
+ Hague Rules on Business and Human Rights Arbitration (the "Rules");
59
+ provided, however, that Licensee may elect not to participate in such
60
+ arbitration, in which event this License (and all rights licensed
61
+ hereunder) shall end immediately. The number of arbitrators shall be one
62
+ unless the Rules require otherwise.
63
+ +
64
+ Unless both the Licensor and Licensee agree to the contrary: (1) All
65
+ documents and information concerning the arbitration shall be public and
66
+ may be disclosed by any party; (2) The repository referred to under
67
+ Article 43 of the Rules shall make available to the public in a timely
68
+ manner all documents concerning the arbitration which are communicated
69
+ to it, including all submissions of the parties, all evidence admitted
70
+ into the record of the proceedings, all transcripts or other recordings
71
+ of hearings and all orders, decisions and awards of the arbitral
72
+ tribunal, subject only to the arbitral tribunal’s powers to take such
73
+ measures as may be necessary to safeguard the integrity of the arbitral
74
+ process pursuant to Articles 18, 33, 41 and 42 of the Rules; and (3)
75
+ Article 26(6) of the Rules shall not apply.
76
+ . Human Rights Laws. The Software shall not be used by any person or
77
+ entity for any systems, activities, or other uses that violate any Human
78
+ Rights Laws. "Human Rights Laws" means any applicable laws,
79
+ regulations, or rules (collectively, "Laws") that protect human,
80
+ civil, labor, privacy, political, environmental, security, economic, due
81
+ process, or similar rights; provided, however, that such Laws are
82
+ consistent and not in conflict with Human Rights Principles (a dispute
83
+ over the consistency or a conflict between Laws and Human Rights
84
+ Principles shall be determined by arbitration as stated above). Where
85
+ the Human Rights Laws of more than one jurisdiction are applicable or in
86
+ conflict with respect to the use of the Software, the Human Rights Laws
87
+ that are most protective of the individuals or groups harmed shall
88
+ apply.
89
+ . Indemnity. Licensee shall hold harmless and indemnify Licensor (and
90
+ any other contributor) against all losses, damages, liabilities,
91
+ deficiencies, claims, actions, judgments, settlements, interest, awards,
92
+ penalties, fines, costs, or expenses of whatever kind, including
93
+ Licensor’s reasonable attorneys’ fees, arising out of or relating to
94
+ Licensee’s use of the Software in violation of Human Rights Laws or
95
+ Human Rights Principles.
96
+ * Failure to Comply. Any failure of Licensee to act according to the
97
+ terms and conditions of this License is both a breach of the License and
98
+ an infringement of the intellectual property rights of the Licensor
99
+ (subject to exceptions under Laws, e.g., fair use). In the event of a
100
+ breach or infringement, the terms and conditions of this License may be
101
+ enforced by Licensor under the Laws of any jurisdiction to which
102
+ Licensee is subject. Licensee also agrees that the Licensor may enforce
103
+ the terms and conditions of this License against Licensee through
104
+ specific performance (or similar remedy under Laws) to the extent
105
+ permitted by Laws. For clarity, except in the event of a breach of this
106
+ License, infringement, or as otherwise stated in this License, Licensor
107
+ may not terminate this License with Licensee.
108
+ * Enforceability and Interpretation. If any term or provision of this
109
+ License is determined to be invalid, illegal, or unenforceable by a
110
+ court of competent jurisdiction, then such invalidity, illegality, or
111
+ unenforceability shall not affect any other term or provision of this
112
+ License or invalidate or render unenforceable such term or provision in
113
+ any other jurisdiction; provided, however, subject to a court
114
+ modification pursuant to the immediately following sentence, if any term
115
+ or provision of this License pertaining to Human Rights Laws or Human
116
+ Rights Principles is deemed invalid, illegal, or unenforceable against
117
+ Licensee by a court of competent jurisdiction, all rights in the
118
+ Software granted to Licensee shall be deemed null and void as between
119
+ Licensor and Licensee. Upon a determination that any term or provision
120
+ is invalid, illegal, or unenforceable, to the extent permitted by Laws,
121
+ the court may modify this License to affect the original purpose that
122
+ the Software be used in compliance with Human Rights Principles and
123
+ Human Rights Laws as closely as possible. The language in this License
124
+ shall be interpreted as to its fair meaning and not strictly for or
125
+ against any party.
126
+ * Disclaimer. TO THE FULL EXTENT ALLOWED BY LAW, THIS SOFTWARE COMES
127
+ "AS IS," WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED, AND LICENSOR AND
128
+ ANY OTHER CONTRIBUTOR SHALL NOT BE LIABLE TO ANYONE FOR ANY DAMAGES OR
129
+ OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE
130
+ OR THIS LICENSE, UNDER ANY KIND OF LEGAL CLAIM.
131
+
132
+ This Hippocratic License is an link:https://ethicalsource.dev[Ethical Source license] and is offered
133
+ for use by licensors and licensees at their own risk, on an "AS IS" basis, and with no warranties
134
+ express or implied, to the maximum extent permitted by Laws.
data/README.adoc ADDED
@@ -0,0 +1,694 @@
1
+ :toc: macro
2
+ :toclevels: 5
3
+ :figure-caption!:
4
+
5
+ :barewords_link: link:https://alchemists.io/articles/barewords_pattern[Barewords]
6
+ :containable_link: link:https://alchemists.io/projects/containable[Containable]
7
+ :infusible_link: link:https://alchemists.io/projects/infusible[Infusible]
8
+ :marameters_link: link:https://alchemists.io/projects/marameters[Marameters]
9
+ :method_parameters_and_arguments_link: link:https://alchemists.io/articles/ruby_method_parameters_and_arguments[Method Parameters and Arguments]
10
+ :method_parameters_link: link:https://docs.ruby-lang.org/en/master/Method.html#method-i-parameters[Method#parameters]
11
+
12
+ = Initable
13
+
14
+ Initable provides automatic initialization of your objects by leveraging the same parameter structure as provided by {method_parameters_link} while adhering to the {barewords_link} pattern for scoping of attributes. This allows you to quickly define what data/dependencies your object should be constructed with while minimizing the amount of code written. 🎉
15
+
16
+ toc::[]
17
+
18
+ == Features
19
+
20
+ * Provides a Domain Specific Language (DSL) for initializing objects.
21
+ * Uses the same data structure as answered by {method_parameters_link}.
22
+ * Adheres to the {barewords_link} pattern.
23
+ * Reduces the amount of code necessary to implement an object.
24
+ * Built atop the {marameters_link} gem.
25
+
26
+ == Requirements
27
+
28
+ . link:https://www.ruby-lang.org[Ruby].
29
+ . A solid understanding of {method_parameters_and_arguments_link}.
30
+
31
+ == Setup
32
+
33
+ To install _with_ security, run:
34
+
35
+ [source,bash]
36
+ ----
37
+ # 💡 Skip this line if you already have the public certificate installed.
38
+ gem cert --add <(curl --compressed --location https://alchemists.io/gems.pem)
39
+ gem install initable --trust-policy HighSecurity
40
+ ----
41
+
42
+ To install _without_ security, run:
43
+
44
+ [source,bash]
45
+ ----
46
+ gem install initable
47
+ ----
48
+
49
+ You can also add the gem directly to your project:
50
+
51
+ [source,bash]
52
+ ----
53
+ bundle add initable
54
+ ----
55
+
56
+ Once the gem is installed, you only need to require it:
57
+
58
+ [source,ruby]
59
+ ----
60
+ require "initable"
61
+ ----
62
+
63
+ == Usage
64
+
65
+ You only need to require this gem, include the module within your class, and configure the necessary parameters for object initialization. The following provides a simple `Person` object that is implemented with and without the use of this gem so you can compare, contrast, and notice the reduction in code used:
66
+
67
+ *With*
68
+
69
+ [source,ruby]
70
+ ----
71
+ require "initable"
72
+
73
+ class Person
74
+ include Initable[%i[keyreq first], %i[keyreq last], %i[key middle]]
75
+
76
+ def name = [first, middle, last].compact.join " "
77
+ end
78
+
79
+ person = Person.new first: "Alfred", last: "Pennyworth"
80
+ #<Person:0x000000012d0711c8 @first="Alfred", @last="Pennyworth", @middle=nil>
81
+
82
+ person.name
83
+ # "Alfred Pennyworth"
84
+
85
+ person.first
86
+ # private method `first' called for #<Person:0x0000000123899eb8> (NoMethodError)
87
+ ----
88
+
89
+ *Without*
90
+
91
+ [source,ruby]
92
+ ----
93
+ class Person
94
+ def initialize first:, last:, middle: nil
95
+ @first = first
96
+ @last = last
97
+ @middle = middle
98
+ end
99
+
100
+ def name = [first, middle, last].compact.join " "
101
+
102
+ private
103
+
104
+ attr_reader :first, :last, :middle
105
+ end
106
+
107
+ person = Person.new first: "Alfred", last: "Pennyworth"
108
+ #<Person:0x0000000123899eb8 @first="Alfred", @last="Pennyworth", @middle=nil>
109
+
110
+ person.name
111
+ # "Alfred Pennyworth"
112
+
113
+ person.first
114
+ # private method `first' called for #<Person:0x0000000123899eb8> (NoMethodError)
115
+ ----
116
+
117
+ Notice, in the examples above, we are able to obtain an instance of `Person` with identical behavior. Even better, using this gem requires less code. We can also see the associated attributes are properly initialized as instance variables. All attributes are _privately_ scoped, by default, so your object doesn't break encapsulation.
118
+
119
+ The rest of this documentation will focus on how to use this gem with the parameters data structure shared {method_parameters_link}.
120
+
121
+ ℹ️ Please note, for the rest of this documentation, anonymous classes will be used for code examples which makes local experimentation a smoother experience within your IRB console since you get a new instance of a class each time without having to create new constants or deal with constant collisions.
122
+
123
+ === Parameters
124
+
125
+ There are eight _kinds_ of parameters you can use in method signatures as supported by {method_parameters_link} and detailed in the {method_parameters_and_arguments_link} article. The format is always kind, name, and default. Example:
126
+
127
+ ----
128
+ [<kind>, <name>, <default>]
129
+ ----
130
+
131
+ 💡 The default (third element) is always optional which, granted, isn't supported by {method_parameters_link} but is part of this DSL so you can supply a default value for optional positional or keyword parameters with minimal effort.
132
+
133
+ As detailed in the {method_parameters_and_arguments_link} article, the order of each kind of parameter matters because if you define them out of order, you'll get a syntax error as you would get when not using this gem to initialize an object. For reference, here's the natural order of parameters for a method signature in case it helps:
134
+
135
+ ----
136
+ %i[req opt rest nokey keyreq key keyrest block]
137
+ ----
138
+
139
+ Simply speaking, this means `req` is always in the first position and `block` is always in the last position. You can skip parameters in between, as necessary, but position is always important regardless of what you use.
140
+
141
+ Each _kind_ of parameter is detailed in the following sections.
142
+
143
+ ==== req
144
+
145
+ Use `req` when you need a _required positional_ parameter:
146
+
147
+ [source,ruby]
148
+ ----
149
+ demo = Class.new do
150
+ include Initable[%i[req example]]
151
+ end
152
+
153
+ demo.new # wrong number of arguments (given 0, expected 1) (ArgumentError)
154
+ demo.new 1 #<#<Class:0x0000000121562940>:0x0000000122244500 @example=1>
155
+ ----
156
+
157
+ ==== opt
158
+
159
+ Use `opt` when you need an _optional positional_ parameter:
160
+
161
+ [source,ruby]
162
+ ----
163
+ demo = Class.new do
164
+ include Initable[%i[opt example]]
165
+ end
166
+
167
+ demo.new #<#<Class:0x00000001215c1a58>:0x0000000124c3d000 @example=nil>
168
+ demo.new 1 #<#<Class:0x0000000120d4f5a0>:0x00000001248b3ee8 @example=1>
169
+ ----
170
+
171
+ You can also provide a default value by supplying a third element for the parameter:
172
+
173
+ [source,ruby]
174
+ ----
175
+ demo = Class.new do
176
+ include Initable[[:opt, :example, 1]]
177
+ end
178
+
179
+ demo.new #<#<Class:0x00000001232d6198>:0x0000000131c31c98 @example=1>
180
+ demo.new 10 #<#<Class:0x00000001232d6198>:0x0000000131d1fb00 @example=10>
181
+ ----
182
+
183
+ ==== rest
184
+
185
+ Use `rest` when you need any number of _optional positional_ parameters:
186
+
187
+ [source,ruby]
188
+ ----
189
+ demo = Class.new do
190
+ include Initable[%i[rest example]]
191
+ end
192
+
193
+ demo.new #<#<Class:0x00000001215ef8e0>:0x0000000125272f88 @example=[]>
194
+ demo.new 1, 2, 3 #<#<Class:0x00000001215ef8e0>:0x0000000124f9c228 @example=[1, 2, 3]>
195
+ ----
196
+
197
+ For anonymous single splats (i.e. `+*+`), don't provide a name. Use only the kind:
198
+
199
+ [source,ruby]
200
+ ----
201
+ demo = Class.new do
202
+ include Initable[[:rest]]
203
+ end
204
+ ----
205
+
206
+ This is useful when needing to forward all positional arguments to the super class.
207
+
208
+ ==== nokey
209
+
210
+ Use `nokey` when you want to prevent use of any _keyword_ parameter (i.e. `+**nil+`):
211
+
212
+ [source,ruby]
213
+ ----
214
+ demo = Class.new do
215
+ include Initable[[:nokey]]
216
+ end
217
+
218
+ demo.new #<#<Class:0x0000000123d1f820>:0x00000001300baf78>
219
+ demo.new a: 1 # wrong number of arguments (given 1, expected 0) (ArgumentError)
220
+ ----
221
+
222
+ ==== keyreq
223
+
224
+ Use `keyreq` when you need a _required keyword_ parameter:
225
+
226
+ [source,ruby]
227
+ ----
228
+ demo = Class.new do
229
+ include Initable[%i[keyreq example]]
230
+ end
231
+
232
+ demo.new # missing keyword: :example (ArgumentError)
233
+ demo.new example: 1 #<#<Class:0x0000000123c99d88>:0x0000000130655ed8 @example=1>
234
+ ----
235
+
236
+ ==== key
237
+
238
+ Use `key` when you need an _optional keyword_ parameter:
239
+
240
+ [source,ruby]
241
+ ----
242
+ demo = Class.new do
243
+ include Initable[%i[key example]]
244
+ end
245
+
246
+ demo.new #<#<Class:0x0000000123c30e78>:0x00000001307b0008 @example=nil>
247
+ demo.new example: 1 #<#<Class:0x0000000123c99d88>:0x0000000130655ed8 @example=1>
248
+ ----
249
+
250
+ You can also provide a default value by supplying a third element for the parameter:
251
+
252
+ [source,ruby]
253
+ ----
254
+ demo = Class.new do
255
+ include Initable[[:key, :example, 1]]
256
+ end
257
+
258
+ demo.new #<#<Class:0x0000000123215b50>:0x000000013007ee88 @example=1>
259
+ demo.new example: 10 #<#<Class:0x0000000123215b50>:0x00000001300ff998 @example=10>
260
+ ----
261
+
262
+ ==== keyrest
263
+
264
+ Use `keyrest` when you need any number of _keyword_ parameters:
265
+
266
+ [source,ruby]
267
+ ----
268
+ demo = Class.new do
269
+ include Initable[%i[keyrest example]]
270
+ end
271
+
272
+ demo.new
273
+ #<#<Class:0x0000000123d117c0>:0x000000013051e3f8 @example={}>
274
+
275
+ demo.new a: 1, b: 2
276
+ #<#<Class:0x0000000123d117c0>:0x000000013069e2c8 @example={:a=>1, :b=>2}>
277
+ ----
278
+
279
+ For anonymous double splats (i.e. `+**+`), don't provide a name. Use only the kind:
280
+
281
+ [source,ruby]
282
+ ----
283
+ demo = Class.new do
284
+ include Initable[[:keyrest]]
285
+ end
286
+ ----
287
+
288
+ This is useful when needing to forward all keyword arguments to the super class.
289
+
290
+ ==== block
291
+
292
+ Use `block` when you need a _block_ parameter:
293
+
294
+ [source,ruby]
295
+ ----
296
+ demo = Class.new do
297
+ include Initable[%i[block example]]
298
+ end
299
+
300
+ demo.new
301
+ #<#<Class:0x0000000123b59b08>:0x000000013193bac0 @example=nil>
302
+
303
+ instance = demo.new { "Hi" }
304
+ #<#<Class:0x0000000123b59b08>:0x0000000131a9a380 @example=#<Proc:0x0000000131a9a358 (irb):45>>
305
+ ----
306
+
307
+ For anonymous blocks (i.e. `+&+`), don't provide a name. Use only the kind:
308
+
309
+ [source,ruby]
310
+ ----
311
+ demo = Class.new do
312
+ include Initable[[:block]]
313
+ end
314
+ ----
315
+
316
+ This is useful when needing to forward a block to the super class.
317
+
318
+ === Defaults
319
+
320
+ You've already seen that you can provide a third element for defaults with optional positional and keyword parameters. Sometimes, though, you might want to use a more complex object as a default (especially if you want the default to be lazy loaded/initialized). For those situations use a `Proc`. Example:
321
+
322
+ [source,ruby]
323
+ ----
324
+ demo = Class.new do
325
+ include Initable[
326
+ [:opt, :one, proc { %w[O n e].join }],
327
+ [:key, :two, proc { Object.new }]
328
+ ]
329
+ end
330
+
331
+ demo.new
332
+ #<#<Class:0x00000001532d4390>:0x0000000153a9b0b0 @one="One", @two=#<Object:0x0000000153a9ade0>>
333
+ ----
334
+
335
+ Notice, for the `one` optional positional parameter, we get a default value of `"One"` once evaluated. For the `two` optional keyword parameter, we get a new instance of `Object` as a default value.
336
+
337
+ ⚠️ At the moment, there a few caveats to be aware of when using procs as defaults:
338
+
339
+ * Use procs because lambdas will throw a `TypeError`.
340
+ * Use procs _with no arguments_ because only the body of the `Proc` is meant to be parsed. Otherwise, you'll get an `ArgumentError`.
341
+ * Ensure each parameter is defined on a distinct line because the body of the `Proc` is extracted at runtime from the source location of the `Proc`. The goal is to improve upon this more in the future.
342
+ * Avoid using within an IRB session because each value will evaluate as `nil`.
343
+
344
+ === Barewords
345
+
346
+ As mentioned earlier, all instances adhere to the {barewords_link} pattern so you have direct access to all data/dependencies via bare word methods. Here's an example with an instance using a required positional and optional keyword parameter.
347
+
348
+ [source,ruby]
349
+ ----
350
+ demo = Class.new do
351
+ include Initable[%i[req one], [:key, :two, 2]]
352
+
353
+ def debug = puts "One: #{one}, Two: #{two}."
354
+ end
355
+
356
+ demo.new(1).debug # One: 1, Two: 2.
357
+ ----
358
+
359
+ Notice, with the `debug` method, only bare words are used as provided by the attribute readers.
360
+
361
+ === Scopes
362
+
363
+ As mentioned earlier, all attributes are scoped -- via `attr_reader` -- as `private` by default but `protected` and `public` scopes are supported too. Here are examples of each:
364
+
365
+ ==== Private
366
+
367
+ [source,ruby]
368
+ ----
369
+ demo = Class.new do
370
+ include Initable[%i[req example]]
371
+ end
372
+
373
+ demo.new(1).example
374
+ # private method `example' called for an instance of #<Class:0x000000012c1f78b8> (NoMethodError)
375
+ ----
376
+
377
+ ==== Protected
378
+
379
+ [source,ruby]
380
+ ----
381
+ demo = Class.new do
382
+ include Initable.protected(%i[req example])
383
+ end
384
+
385
+ demo.new(1).example
386
+ # protected method `example' called for an instance of #<Class:0x000000012b316ec0> (NoMethodError)
387
+ ----
388
+
389
+ ==== Public
390
+
391
+ [source,ruby]
392
+ ----
393
+ demo = Class.new do
394
+ include Initable.public(%i[req example])
395
+ end
396
+
397
+ demo.new(1).example
398
+ # 1
399
+ ----
400
+
401
+ ==== Combinations
402
+
403
+ You can combine scopes, if desired, as well. Here's an example using three required positional parameters with different scopes:
404
+
405
+ [source,ruby]
406
+ ----
407
+ demo = Class.new do
408
+ include Initable[%i[req one]]
409
+ include Initable.protected(%i[req two])
410
+ include Initable.public(%i[req three])
411
+ end
412
+
413
+ instance = demo.new 1, 2, 3
414
+ #<#<Class:0x000000012c4d3708>:0x00000001501fbc78 @one=1, @two=2, @three=3>
415
+
416
+ instance.one
417
+ # private method `one' called for an instance of #<Class:0x000000012c4d3708> (NoMethodError)
418
+
419
+ instance.two
420
+ # protected method `two' called for an instance of #<Class:0x000000012c4d3708> (NoMethodError)
421
+
422
+ instance.three
423
+ # 3
424
+ ----
425
+
426
+ ⚠️ While convenient to initialize an object with different scopes, this does introduce additional multiple inheritance in your object ancestry. While not necessarily bad, if your object isn't overly complicated or requires more than three parameters (🎗️ Don't forget to adhere to the _rule of three_), you might need to break your class into smaller dependencies and/or switch to manually defining the `initialize` method.
427
+
428
+ === Inheritance
429
+
430
+ Inheritance works similar to parent/child relationships as found in standard Ruby classes with a few enhancements thrown in for convenience. Several examples are provided below. For each, there is an identical implementation using Plain Old Ruby Objects (POROs) so you can contrast/compare for clarity.
431
+
432
+ [source,ruby]
433
+ ----
434
+ parent = Class.new do
435
+ include Initable.protected(%i[req one])
436
+ end
437
+
438
+ child = Class.new parent do
439
+ include Initable[[:opt, :two, 2]]
440
+ end
441
+
442
+ parent.new 1
443
+ #<#<Class:0x00000001252988f0>:0x00000001265f0c90 @one=1>
444
+
445
+ child.new 1
446
+ #<#<Class:0x0000000123a5a158>:0x00000001254beb20 @one=1, @two=2>
447
+
448
+ child.new 10, 20
449
+ #<#<Class:0x000000012261a828>:0x0000000126973d40 @one=10, @two=20>
450
+ ----
451
+
452
+ .Plain Implementation
453
+ [%collapsible]
454
+ ====
455
+ [source,ruby]
456
+ ----
457
+ parent = Class.new do
458
+ def initialize one
459
+ @one = one
460
+ end
461
+
462
+ protected
463
+
464
+ attr_reader :one
465
+ end
466
+
467
+ child = Class.new parent do
468
+ def initialize one, two = 2
469
+ super one
470
+ @two = two
471
+ end
472
+
473
+ private
474
+
475
+ attr_reader :two
476
+ end
477
+
478
+ parent.new 1
479
+ #<#<Class:0x0000000127b3f790>:0x0000000134abe368 @one=1>
480
+
481
+ child.new 1
482
+ #<#<Class:0x0000000127b3f5b0>:0x0000000134b16748 @one=1, @two=2>
483
+
484
+ child.new 10, 20
485
+ #<#<Class:0x0000000127b3f5b0>:0x0000000134b91880 @one=10, @two=20>
486
+ ----
487
+ ====
488
+
489
+ Notice the `child` instance has access to both the `one` and `two` attributes where `one` is defined as _protected_ by the `parent` and `two` is defined as _private_ for the `child`. This is no different in how you'd subclass without using this gem. You only need to define the attributes you need in the `child` class since there is no need to redefine what the `parent` already has defined. This gem will handle proper setup of your instance variables as well as forwarding, via `super`, any/all attributes to the `parent` as necessary. The automatic forwarding, via `super`, applies for all parameters.
490
+
491
+ ==== Positionals
492
+
493
+ [source,ruby]
494
+ ----
495
+ parent = Class.new do
496
+ include Initable.protected(%i[req one], [:opt, :two, 2])
497
+ end
498
+
499
+ child = Class.new parent do
500
+ include Initable[%i[req three], [:opt, :two, 2]]
501
+ end
502
+
503
+ child.new 1, 3
504
+ #<#<Class:0x0000000126012ee0>:0x0000000128591478 @one=1, @two=2, @three=3>
505
+
506
+ child.new 1, 3, 20
507
+ #<#<Class:0x0000000126012ee0>:0x00000001286353e8 @one=1, @two=20, @three=3>
508
+ ----
509
+
510
+ .Plain Implementation
511
+ [%collapsible]
512
+ ====
513
+ [source,ruby]
514
+ ----
515
+ parent = Class.new do
516
+ def initialize one, two = 2
517
+ @one = one
518
+ @two = two
519
+ end
520
+
521
+ private
522
+
523
+ attr_reader :one, :two
524
+ end
525
+
526
+ child = Class.new parent do
527
+ def initialize one, three, two = 2
528
+ super one, two
529
+ @three = three
530
+ end
531
+
532
+ private
533
+
534
+ attr_reader :three
535
+ end
536
+
537
+ child.new 1, 3
538
+ #<#<Class:0x0000000126076e18>:0x0000000128297240 @one=1, @two=2, @three=3>
539
+
540
+ child.new 1, 3, 20
541
+ #<#<Class:0x0000000126076e18>:0x00000001284344b8 @one=1, @two=20, @three=3>
542
+ ----
543
+ ====
544
+
545
+ Positional parameters are less flexible than keyword parameters especially when optional parameters are involved because the order of parameters matters and the `two` parameter with a default of `2` has to be repeated in the child so `two` can be forwarded by `super` when not supplied.
546
+
547
+ ==== Keywords
548
+
549
+ [source,ruby]
550
+ ----
551
+ parent = Class.new do
552
+ include Initable.protected(%i[keyreq one], [:key, :two, 2])
553
+ end
554
+
555
+ child = Class.new parent do
556
+ include Initable[%i[keyreq three], [:key, :four, 4]]
557
+ end
558
+
559
+ child.new one: 1, three: 3
560
+ #<#<Class:0x000000012e052ee8>:0x0000000138311800 @one=1, @two=2, @three=3, @four=4>
561
+
562
+ child.new one: 1, two: 20, three: 3, four: 40
563
+ #<#<Class:0x000000012e052ee8>:0x00000001383d0b10 @one=1, @two=20, @three=3, @four=40>
564
+ ----
565
+
566
+ .Plain Implementation
567
+ [%collapsible]
568
+ ====
569
+ [source,ruby]
570
+ ----
571
+ parent = Class.new do
572
+ def initialize one:, two: 2
573
+ @one = one
574
+ @two = two
575
+ end
576
+
577
+ private
578
+
579
+ attr_reader :one, :two
580
+ end
581
+
582
+ child = Class.new parent do
583
+ def initialize(three:, four: 4, **)
584
+ super(**)
585
+ @three = three
586
+ @four = four
587
+ end
588
+
589
+ private
590
+
591
+ attr_reader :three, :four
592
+ end
593
+
594
+ child.new one: 1, three: 3
595
+ #<#<Class:0x000000012e052ee8>:0x0000000138311800 @one=1, @two=2, @three=3, @four=4>
596
+
597
+ child.new one: 1, two: 20, three: 3, four: 40
598
+ #<#<Class:0x000000012a558680>:0x0000000139831c80 @one=1, @two=20, @three=3, @four=40>
599
+ ----
600
+ ====
601
+
602
+ Due to the power of keyword parameters, we don't have to redefine defaults in the `child` and can simply forward any/all missing arguments to the `parent`. This happens automatically but you can see how this done in the plain implementation.
603
+
604
+ ==== Blocks
605
+
606
+ [source,ruby]
607
+ ----
608
+ parent = Class.new do
609
+ include Initable.protected(%i[block function])
610
+ end
611
+
612
+ child = Class.new parent
613
+
614
+
615
+ child.new { "demo" }
616
+ #<#<Class:0x0000000129c92320>:0x0000000139c95538 @function=#<Proc:0x0000000139c95470 (irb):50>>
617
+ ----
618
+
619
+ .Plain Implementation
620
+ [%collapsible]
621
+ ====
622
+ [source,ruby]
623
+ ----
624
+ parent = Class.new do
625
+ def initialize &function
626
+ @function = function
627
+ end
628
+
629
+ private
630
+
631
+ attr_reader :function
632
+ end
633
+
634
+ child = Class.new parent
635
+
636
+ child.new { "demo" }
637
+ #<#<Class:0x000000012a5f0160>:0x0000000138375580 @function=#<Proc:0x0000000138375508 (irb):65>>
638
+ ----
639
+ ====
640
+
641
+ With blocks, you only have to name them in the `parent` and they will be forwarded by the child. Keep in mind that if you only need to pass the block to the parent but want to use a `block_given?` check before messaging the function in your parent class, then you don't need to use this gem for those situations.
642
+
643
+ === Guidelines
644
+
645
+ The following is worth adhering to:
646
+
647
+ * Use the _rule of three_ where you only don't use more than three parameters for your method signature. Anything more than that and you have an unborn object that needs a name for dependency injection instead. 💡 For advanced dependency management, consider using {containable_link} and/or {infusible_link}.
648
+ * Avoid using complex logic in proc-wrapped defaults. Procs should only be used for lazy loading of default objects.
649
+
650
+ == Development
651
+
652
+ To contribute, run:
653
+
654
+ [source,bash]
655
+ ----
656
+ git clone https://github.com/bkuhlmann/initable
657
+ cd initable
658
+ bin/setup
659
+ ----
660
+
661
+ You can also use the IRB console for direct access to all objects:
662
+
663
+ [source,bash]
664
+ ----
665
+ bin/console
666
+ ----
667
+
668
+ == Tests
669
+
670
+ To test, run:
671
+
672
+ [source,bash]
673
+ ----
674
+ bin/rake
675
+ ----
676
+
677
+ == link:https://alchemists.io/policies/license[License]
678
+
679
+ == link:https://alchemists.io/policies/security[Security]
680
+
681
+ == link:https://alchemists.io/policies/code_of_conduct[Code of Conduct]
682
+
683
+ == link:https://alchemists.io/policies/contributions[Contributions]
684
+
685
+ == link:https://alchemists.io/policies/developer_certificate_of_origin[Developer Certificate of Origin]
686
+
687
+ == link:https://alchemists.io/projects/initable/versions[Versions]
688
+
689
+ == link:https://alchemists.io/community[Community]
690
+
691
+ == Credits
692
+
693
+ * Built with link:https://alchemists.io/projects/gemsmith[Gemsmith].
694
+ * Engineered by link:https://alchemists.io/team/brooke_kuhlmann[Brooke Kuhlmann].
data/initable.gemspec ADDED
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "initable"
5
+ spec.version = "0.0.0"
6
+ spec.authors = ["Brooke Kuhlmann"]
7
+ spec.email = ["brooke@alchemists.io"]
8
+ spec.homepage = "https://alchemists.io/projects/initable"
9
+ spec.summary = "An automatic object initializer."
10
+ spec.license = "Hippocratic-2.1"
11
+
12
+ spec.metadata = {
13
+ "bug_tracker_uri" => "https://github.com/bkuhlmann/initable/issues",
14
+ "changelog_uri" => "https://alchemists.io/projects/initable/versions",
15
+ "homepage_uri" => "https://alchemists.io/projects/initable",
16
+ "funding_uri" => "https://github.com/sponsors/bkuhlmann",
17
+ "label" => "Initable",
18
+ "rubygems_mfa_required" => "true",
19
+ "source_code_uri" => "https://github.com/bkuhlmann/initable"
20
+ }
21
+
22
+ spec.signing_key = Gem.default_key_path
23
+ spec.cert_chain = [Gem.default_cert_path]
24
+
25
+ spec.required_ruby_version = "~> 3.4"
26
+ spec.add_dependency "marameters", "~> 4.0"
27
+
28
+ spec.extra_rdoc_files = Dir["README*", "LICENSE*"]
29
+ spec.files = Dir["*.gemspec", "lib/**/*"]
30
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "marameters"
4
+
5
+ module Initable
6
+ # Builds initialization behavior.
7
+ # :reek:TooManyInstanceVariables
8
+ class Builder < Module
9
+ def initialize *parameters, scope: :private, marameters: Marameters
10
+ super()
11
+
12
+ @parameters = marameters.for parameters
13
+ @scope = scope
14
+ @marameters = marameters
15
+ @names = @parameters.names.compact
16
+ @instance_module = Module.new.set_temporary_name "initable"
17
+
18
+ freeze
19
+ end
20
+
21
+ def included descendant
22
+ super
23
+ define_initialize descendant
24
+ descendant.include instance_module
25
+ end
26
+
27
+ private
28
+
29
+ attr_reader :scope, :parameters, :marameters, :names, :instance_module
30
+
31
+ def define_initialize descendant,
32
+ inheritor: Marameters::Signatures::Inheritor.new,
33
+ forwarder: Marameters::Signatures::Super.new
34
+ ancestor = marameters.of(descendant, :initialize).first
35
+ signature = inheritor.call(ancestor, parameters).then { |params| marameters.signature params }
36
+
37
+ instance_module.module_eval <<-METHOD, __FILE__, __LINE__ + 1
38
+ def initialize(#{signature})
39
+ super(#{forwarder.call ancestor, parameters})
40
+ #{build_instance_variables ancestor}
41
+ end
42
+ METHOD
43
+
44
+ define_readers ancestor
45
+ end
46
+
47
+ def build_instance_variables ancestor
48
+ (names - ancestor.names).map { |name| "@#{name} = #{name}" }
49
+ .join "\n"
50
+ end
51
+
52
+ def define_readers ancestor
53
+ (names - ancestor.names).each do |name|
54
+ symbol = name.inspect
55
+
56
+ instance_module.module_eval <<-READERS, __FILE__, __LINE__ + 1
57
+ #{compute_scope} attr_reader #{symbol}
58
+ READERS
59
+ end
60
+ end
61
+
62
+ def compute_scope = METHOD_SCOPES.include?(scope) ? scope : :private
63
+ end
64
+ end
data/lib/initable.rb ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "initable/builder"
4
+
5
+ # Main namespace.
6
+ module Initable
7
+ METHOD_SCOPES = %i[public protected private].freeze
8
+
9
+ def self.[](*) = Builder.new(*)
10
+
11
+ def self.protected(*) = Builder.new(*, scope: __method__)
12
+
13
+ def self.public(*) = Builder.new(*, scope: __method__)
14
+ end
data.tar.gz.sig ADDED
Binary file
metadata ADDED
@@ -0,0 +1,94 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: initable
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Brooke Kuhlmann
8
+ bindir: bin
9
+ cert_chain:
10
+ - |
11
+ -----BEGIN CERTIFICATE-----
12
+ MIIEeDCCAuCgAwIBAgIBATANBgkqhkiG9w0BAQsFADBBMQ8wDQYDVQQDDAZicm9v
13
+ a2UxGjAYBgoJkiaJk/IsZAEZFgphbGNoZW1pc3RzMRIwEAYKCZImiZPyLGQBGRYC
14
+ aW8wHhcNMjMwMzIyMTYxNDQxWhcNMjUwMzIxMTYxNDQxWjBBMQ8wDQYDVQQDDAZi
15
+ cm9va2UxGjAYBgoJkiaJk/IsZAEZFgphbGNoZW1pc3RzMRIwEAYKCZImiZPyLGQB
16
+ GRYCaW8wggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCro8tj5/E1Hg88
17
+ f4qfiwPVd2zJQHvdYt4GHVvuHRRgx4HGhJuNp+4BId08RBn7V6V1MW6MY3kezRBs
18
+ M+7QOQ4b1xNLTvY7FYQB1wGK5a4x7TTokDrPYQxDB2jmsdDYCzVbIMrAvUfcecRi
19
+ khyGZCdByiiCl4fKv77P12tTT+NfsvXkLt/AYCGwjOUyGKTQ01Z6eC09T27GayPH
20
+ QQvIkakyFgcJtzSyGzs8bzK5q9u7wQ12MNTjJoXzW69lqp0oNvDylu81EiSUb5S6
21
+ QzzPxZBiRB1sgtbt1gUbVI262ZDq1gR+HxPFmp+Cgt7ZLIJZAtesQvtcMzseXpfn
22
+ hpmm0Sw22KGhRAy/mqHBRhDl5HqS1SJp2Ko3lcnpXeFResp0HNlt8NSu13vhC08j
23
+ GUHU9MyIXbFOsnp3K3ADrAVjPWop8EZkmUR3MV/CUm00w2cZHCSGiXl1KMpiVKvk
24
+ Ywr1gd2ZME4QLSo+EXUtLxDUa/W3xnBS8dBOuMMz02FPWYr3PN8CAwEAAaN7MHkw
25
+ CQYDVR0TBAIwADALBgNVHQ8EBAMCBLAwHQYDVR0OBBYEFAFgmv0tYMZnItuPycSM
26
+ F5wykJEVMB8GA1UdEQQYMBaBFGJyb29rZUBhbGNoZW1pc3RzLmlvMB8GA1UdEgQY
27
+ MBaBFGJyb29rZUBhbGNoZW1pc3RzLmlvMA0GCSqGSIb3DQEBCwUAA4IBgQAX+EGY
28
+ 9RLYGxF1VLZz+G1ACQc4uyrCB6kXwI06kzUa5dF9tPXqTX9ffnz3/W8ck2IQhKzu
29
+ MKO2FVijzbDWTsZeZGglS4E+4Jxpau1lU9HhOIcKolv6LeC6UdALTFudY+GLb8Xw
30
+ REXgaJkjzzhkUSILmEnRwEbY08dVSl7ZAaxVI679vfI2yapLlIwpbBgmQTiTvPr3
31
+ qyyLUno9flYEOv9fmGHunSrM+gE0/0niGTXa5GgXBXYGS2he4LQGgSBfGp/cTwMU
32
+ rDKJRcusZ12lNBeDfgqACz/BBJF8FLodgk6rGMRZz7+ZmjjHEmpG5bQpR6Q2BuWL
33
+ XMtYk/QzaWuhiR7pWjiF8jbdd7RO6or0ohq7iFkokz/5xrtQ/vPzU2RQ3Qc6YaKw
34
+ 3n5C8/6Zh9DYTkpcwPSuIfAga6wf4nXc9m6JAw8AuMLaiWN/r/2s4zJsUHYERJEu
35
+ gZGm4JqtuSg8pYjPeIJxS960owq+SfuC+jxqmRA54BisFCv/0VOJi7tiJVY=
36
+ -----END CERTIFICATE-----
37
+ date: 2025-01-01 00:00:00.000000000 Z
38
+ dependencies:
39
+ - !ruby/object:Gem::Dependency
40
+ name: marameters
41
+ requirement: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - "~>"
44
+ - !ruby/object:Gem::Version
45
+ version: '4.0'
46
+ type: :runtime
47
+ prerelease: false
48
+ version_requirements: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - "~>"
51
+ - !ruby/object:Gem::Version
52
+ version: '4.0'
53
+ email:
54
+ - brooke@alchemists.io
55
+ executables: []
56
+ extensions: []
57
+ extra_rdoc_files:
58
+ - README.adoc
59
+ - LICENSE.adoc
60
+ files:
61
+ - LICENSE.adoc
62
+ - README.adoc
63
+ - initable.gemspec
64
+ - lib/initable.rb
65
+ - lib/initable/builder.rb
66
+ homepage: https://alchemists.io/projects/initable
67
+ licenses:
68
+ - Hippocratic-2.1
69
+ metadata:
70
+ bug_tracker_uri: https://github.com/bkuhlmann/initable/issues
71
+ changelog_uri: https://alchemists.io/projects/initable/versions
72
+ homepage_uri: https://alchemists.io/projects/initable
73
+ funding_uri: https://github.com/sponsors/bkuhlmann
74
+ label: Initable
75
+ rubygems_mfa_required: 'true'
76
+ source_code_uri: https://github.com/bkuhlmann/initable
77
+ rdoc_options: []
78
+ require_paths:
79
+ - lib
80
+ required_ruby_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - "~>"
83
+ - !ruby/object:Gem::Version
84
+ version: '3.4'
85
+ required_rubygems_version: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ requirements: []
91
+ rubygems_version: 3.6.2
92
+ specification_version: 4
93
+ summary: An automatic object initializer.
94
+ test_files: []
metadata.gz.sig ADDED
Binary file