declarative_initialization 0.1.0

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 2def6406dabc72b117248ec302ac3fbb6b69dc2a67721abd229a1f5787ae50ce
4
+ data.tar.gz: 1bfa5430363018213e882a330e5ee83267b65a282a7cfb4f3439243a70e79887
5
+ SHA512:
6
+ metadata.gz: 150ee62b3d7034af1b9d171bbfe6f472914439c1b9af558b78f34c4e4e66a6fdf28f870af998d00fc0d73f2ef699f76cfe3443a675cdff047668d66f15179e87
7
+ data.tar.gz: 84dabfae84540cd6d7e0fe130e33edd1eb4126fc5a8e32d83fea676c2401c297ae70fe6de6b6c4210228ea86d7789b90be5c17311af5880e320a701b405aa3b9
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,37 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+
6
+ Style/StringLiterals:
7
+ Enabled: true
8
+ EnforcedStyle: double_quotes
9
+
10
+ Style/StringLiteralsInInterpolation:
11
+ Enabled: true
12
+ EnforcedStyle: double_quotes
13
+
14
+ Style/Documentation:
15
+ Enabled: false
16
+
17
+ Layout/LineLength:
18
+ Max: 120
19
+
20
+ # Here down -- just getting our core level to pass
21
+ Metrics/BlockLength:
22
+ Enabled: false
23
+
24
+ Metrics/MethodLength:
25
+ AllowedMethods: [initialize, initialize_with]
26
+
27
+ Metrics/AbcSize:
28
+ Max: 42
29
+
30
+ Metrics/CyclomaticComplexity:
31
+ Max: 12
32
+
33
+ Metrics/PerceivedComplexity:
34
+ Max: 13
35
+
36
+ Gemspec/RequireMFA:
37
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-03-05
4
+
5
+ - Initial release
data/CODEOWNERS ADDED
@@ -0,0 +1 @@
1
+ * @teamshares/platform
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at kali@teamshares.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # DeclarativeInitialization
2
+
3
+ Boilerplate slows down devs and irritates everyone, plus the added cruft makes it harder to scan for the actual logic in a given file.
4
+
5
+ This is a small layer to support declarative initialization _specifically for simple keyword-based classes_.
6
+
7
+ ## Usage
8
+
9
+ Given a standard ruby class like so:
10
+
11
+ ```ruby
12
+ class SomeObject
13
+ def initialize(foo:, bar:, baz: "default value")
14
+ @foo = foo
15
+ @bar = bar
16
+ @baz = baz
17
+ end
18
+
19
+ attr_reader :foo, :bar, :baz
20
+ end
21
+ ```
22
+
23
+ With this library it can be simplified to:
24
+
25
+ ```ruby
26
+ class SomeObject
27
+ include DeclarativeInitialization
28
+
29
+ initialize_with :foo, :bar, baz: "default value"
30
+ end
31
+ ```
32
+ ## Quick note on naming
33
+
34
+ The gem name is `declarative_initialization` because there's already a very outdated gem claiming the `initialize_with` name.
35
+
36
+ We've set up an alias, however, so you can do either `include DeclarativeInitialization` _or_ `include InitializeWith`.
37
+
38
+ FWIW in practice at Teamshares we just `include DeclarativeInitialization` in the base class for all our View Components.
39
+
40
+ ### Custom logic
41
+
42
+ Sometimes the existing `initialize` method also does other work, for instance setting initial values for additional instance variables that aren't passed in directly.
43
+
44
+ We support that by passing an optional block to `initialize_with` -- for instance, in the example above if the original version also set `@bang = foo * bar`, we could support that by changing the updated version to:
45
+
46
+ ```ruby
47
+ initialize_with :foo, :bar, baz: "default value" do
48
+ @bang = @foo * @bar
49
+ end
50
+ ```
51
+
52
+ ### Edge cases
53
+
54
+ * Accepting a block: this is handled automatically -- if a block was provided to the Foo.new call, it'll be made available as `@block`/`attr_reader :block`
55
+
56
+ * If a method with same name already exists, we log a warning and do not create the `attr_reader`. In that case you'll need to reference the instance variable directly.
57
+
58
+ * Because of this, best practice when referencing variables in the post-initialize block is use `@foo` rather than relying on the `foo` attr_reader
59
+
60
+ * Due to ruby syntax limitations, we do not support referencing other fields directly in the declaration:
61
+
62
+ * Does _not_ work:
63
+ ```ruby
64
+ initialize_with :user, company: user.employer
65
+ ```
66
+ * Workaround:
67
+ ```ruby
68
+ initialize_with :user, company: nil do
69
+ @company ||= @user.employer
70
+ end
71
+ ```
72
+
73
+ * If using `initialize_with` on a subclass where the superclass defines `initialize`, we will _not_ automatically call `super`, because if we do we get this `RuntimeError`:
74
+ > implicit argument passing of super from method defined by define_method() is not supported. Specify all arguments explicitly.
75
+
76
+ * If you need to call `super` from the block passed into `initialize_with` (unusual edge case, subclass requires different arguments than parent):
77
+
78
+ * Does _not_ work (due to `instance_exec` changing execution context but _not_ the method lookup chain):
79
+ ```ruby
80
+ initialize_with :foo do
81
+ super(bar: 123)
82
+ end
83
+ ```
84
+ * Workaround _possible_ (but really, probably more understandable to just fall back to manually writing `def initialize`):
85
+ ```ruby
86
+ initialize_with :foo do
87
+ parent_initialize = method(:initialize).super_method
88
+ parent_initialize.call(bar: 123)
89
+ end
90
+ ```
91
+
92
+ * If you find yourself backed into a weird corner, just use a plain ole `def initialize`! This library is meant to make the easy cases less work, but there's no requirement that you must use it for every super complex case you run into. :)
93
+
94
+ ## Development
95
+
96
+ 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.
97
+
98
+ 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).
99
+
100
+ ## Contributing
101
+
102
+ Bug reports and pull requests are welcome on GitHub at https://github.com/teamshares/declarative_initialization. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/teamshares/declarative_initialization/blob/main/CODE_OF_CONDUCT.md).
103
+
104
+ ## Code of Conduct
105
+
106
+ Everyone interacting in the DeclarativeInitialization project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/teamshares/declarative_initialization/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DeclarativeInitialization
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "declarative_initialization/version"
4
+ require "logger"
5
+
6
+ module DeclarativeInitialization
7
+ def self.included(base)
8
+ base.class_eval do
9
+ include InstanceMethods
10
+ extend ClassMethods
11
+ end
12
+ end
13
+
14
+ module ClassMethods
15
+ def initialize_with(*args, **kwargs, &post_initialize_block)
16
+ declared = args + kwargs.keys
17
+ raise ArgumentError, "initialize_with expects to receive symbols" unless declared.all? { |arg| arg.is_a?(Symbol) }
18
+
19
+ defaults = kwargs
20
+
21
+ define_method(:initialize) do |*given_args, **given_kwargs, &block|
22
+ class_name = self.class.name || "Anonymous Class"
23
+ raise ArgumentError, "[#{class_name}] Only accepts keyword arguments" unless given_args.empty?
24
+
25
+ missing = declared - given_kwargs.keys - defaults.keys
26
+ extra = given_kwargs.keys - declared
27
+
28
+ raise ArgumentError, "[#{class_name}] Missing keyword arguments: #{missing.join(", ")}" unless missing.empty?
29
+ raise ArgumentError, "[#{class_name}] Unknown keyword arguments: #{extra.join(", ")}" unless extra.empty?
30
+
31
+ declared.each do |key|
32
+ instance_variable_set(:"@#{key}", given_kwargs.fetch(key, defaults[key]))
33
+ if respond_to?(key, true)
34
+ __logger.warn "Method ##{key} already exists on #{self.class.name}. Skipping attr_reader generation."
35
+ else
36
+ self.class.send(:attr_reader, key)
37
+ end
38
+ end
39
+
40
+ if block # Automatically record any block passed to .new as an instance variable
41
+ instance_variable_set(:@block, block)
42
+ self.class.send(:attr_reader, :block) unless respond_to?(:block)
43
+ end
44
+
45
+ instance_exec(&post_initialize_block) if post_initialize_block
46
+ end
47
+ end
48
+ end
49
+
50
+ module InstanceMethods
51
+ def __logger
52
+ @__logger ||= begin
53
+ Rails.logger
54
+ rescue NameError
55
+ Logger.new($stdout)
56
+ end
57
+ end
58
+ end
59
+ end
60
+
61
+ # Set up an alias so you can also do `include InitializeWith`
62
+ module InitializeWith
63
+ def self.included(base)
64
+ base.class_eval do
65
+ include DeclarativeInitialization
66
+ end
67
+ end
68
+ end
metadata ADDED
@@ -0,0 +1,55 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: declarative_initialization
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Kali Donovan
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-03-07 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: A declarative replacement for `def initialize` in keyword-argument-based
14
+ POROs.
15
+ email:
16
+ - kali@teamshares.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".rspec"
22
+ - ".rubocop.yml"
23
+ - CHANGELOG.md
24
+ - CODEOWNERS
25
+ - CODE_OF_CONDUCT.md
26
+ - README.md
27
+ - Rakefile
28
+ - lib/declarative_initialization.rb
29
+ - lib/declarative_initialization/version.rb
30
+ homepage: https://github.com/teamshares/declarative_initialization
31
+ licenses: []
32
+ metadata:
33
+ homepage_uri: https://github.com/teamshares/declarative_initialization
34
+ source_code_uri: https://github.com/teamshares/declarative_initialization
35
+ changelog_uri: https://github.com/teamshares/declarative_initialization/blob/main/CHANGELOG.md
36
+ post_install_message:
37
+ rdoc_options: []
38
+ require_paths:
39
+ - lib
40
+ required_ruby_version: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: 3.0.0
45
+ required_rubygems_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '0'
50
+ requirements: []
51
+ rubygems_version: 3.4.10
52
+ signing_key:
53
+ specification_version: 4
54
+ summary: Reduce initialization boilerplate for Ruby classes
55
+ test_files: []