key_value_coding 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: 7d930f48bc39ac156387930313364ad48abd30dc75720025cf6b13f6d57c1f1b
4
+ data.tar.gz: 2e9327e5880a0725081d2a7ca1566c1d0ced487d7664d31e889c7361506e503e
5
+ SHA512:
6
+ metadata.gz: 1acec129c687cde176832bd4800526200f271a6d939128e0c28b4ad5050bcde81fa813b7e496f57f28f76d367b0958df87b7ef1c65658a8027734fa6a346ef54
7
+ data.tar.gz: 67a7dd6162051bce818add934625e74149b7fc99c2be70fc0fdac0a5b2073a18597939ab7d55102a9b294a69da899d79260d15d715b7a2408e18548e5ab1ef8e
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-02-02
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Pierre de La Morinerie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,175 @@
1
+ # KeyValueCoding
2
+
3
+ This gem is a port of Cocoa's Key-Value Coding to Ruby.
4
+
5
+ [Key-Value Coding](https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/KeyValueCoding.html) is a paradigm introduced in Cocoa, that allows to:
6
+ - query an object property using a string (like `public_send`),
7
+ - traverse an object hierarchy using a key path (like `dig`).
8
+
9
+ ## Why?
10
+
11
+ In Ruby, traversing an PORO hierarchy is easy:
12
+ ```ruby
13
+ company.managers.first.name
14
+ ```
15
+
16
+ Traversing a JSON-like hierarchy of arrays and hashes is also easy:
17
+ ```ruby
18
+ data.dig(:company, :managers, 1, :name)
19
+ ```
20
+
21
+ But only Array, Hashes and Struct implement `dig` – not all POROs. As a result:
22
+ - operating on mixed hierarchies of POROs and hashes is painful,
23
+ - operating on multiple collections items is painful.
24
+
25
+ Key-Value Coding solves this with a common interface for POROs and hashes.
26
+
27
+ ### Common interface for POROs and hashes
28
+
29
+ ```ruby
30
+ record.company # Specific to objects
31
+ data[:company] # Specific to hashes
32
+ object.value_for_key(:company) # Works with both!
33
+ ```
34
+
35
+ ### Traversing a mixed hierarchy of PORO and hashes
36
+
37
+ ```ruby
38
+ company.address[:street] # Meh
39
+ data.dig(:company, :address).street # Ugh
40
+ data.value_for_key_path("company.address.street") # Nice!
41
+ ```
42
+
43
+ ### Operating on multiple collection items at once
44
+
45
+ ```ruby
46
+ company.managers.map { it[:name] }.map(&:upcase) # Meh
47
+ company.value_for_key_path("name.upcase") # Nice!
48
+ ```
49
+
50
+ ### Set a value on a mixed hierarchy of PORO and hashes
51
+
52
+ ```ruby
53
+ record.company?.address?[:street] = "Ash Tree Lane 12" # Meh
54
+ record.set_value("Ash Tree Lane 12" for_key_path: "company.address.street") # Nice!
55
+ ```
56
+
57
+ ## Installation
58
+
59
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
60
+
61
+ Install the gem and add to the application's Gemfile by executing:
62
+
63
+ ```bash
64
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
65
+ ```
66
+
67
+ If bundler is not being used to manage dependencies, install the gem by executing:
68
+
69
+ ```bash
70
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
71
+ ```
72
+
73
+ ## Usage
74
+
75
+ ### `Object#value_for_key`
76
+
77
+ ```ruby
78
+ manager.value_for_key(:name) # "Don Draper"
79
+ ```
80
+
81
+ Get an object value (like `public_send`, but also operate on hashes and instance variables).
82
+
83
+ - For objects, the value returned by invoking the corresponding method is returned, or the corresponding instance variable if any.
84
+ ```ruby
85
+ manager.value_for_key(:name) # "Don Draper"
86
+ ```
87
+ - For hashes, the value for the corresponding hash key is returned.
88
+ ```ruby
89
+ { name: "Don Draper" }.value_for_key(:name) # "Don Draper"
90
+ ```
91
+ - For arrays, the collection of key values for all items is returned (like ActiveSupport's `pick` method).
92
+ ```ruby
93
+ managers = [ { name: "Don Draper" }, { name: "Peggy Olson" }]
94
+ managers.value_for_key(:name) # [ "Don Draper", "Peggy Olson" ]
95
+ ```
96
+
97
+ If the key doesn't exist, `value_for_undefined_key` is called (which usually results in a `KeyValueCoding::UndefinedKey` exception).
98
+
99
+ ### `Object#values_for_keys`
100
+
101
+ ```ruby
102
+ manager.value_for_keys(:name, :birth_date) # { name: "Don Draper", birth_date: "01/06/1926" }
103
+ ```
104
+
105
+ Get several values of an object (like `pluck` or `slice`, but works on objects as well as hashes).
106
+
107
+ For each key, `value_for_key` is used to retrieve the value.
108
+
109
+ If one of the keys doesn't exist, `value_for_undefined_key` is called (which usually results in a `KeyValueCoding::UndefinedKey` exception).
110
+
111
+ ### `Object#value_for_key_path`
112
+
113
+ ```ruby
114
+ manager.value_for_key_path("name.length") # 10
115
+ ```
116
+
117
+ Get the value of a chain of keys (like object traversal, but works also on hashes).
118
+
119
+ For each dot-separated component of the key-path, `value_for_key` is used to retrieve the value.
120
+
121
+ If one of the keys doesn't exist, `value_for_undefined_key` is called (which usually results in a `KeyValueCoding::UndefinedKey` exception).
122
+
123
+ ### `Object#set_value(value, for_key:)`
124
+
125
+ ```ruby
126
+ manager.set_value("Richard Whitman", for_key: :name)
127
+ ```
128
+
129
+ Set the value of a key (like object assignement, but also work on hashes).
130
+
131
+ If the key doesn't exist, `value_for_undefined_key` is called (which usually results in a `KeyValueCoding::UndefinedKey` exception).
132
+
133
+ ### `Object#set_value(value, for_key_path:)`
134
+
135
+ ```ruby
136
+ record.set_value("Richard Whitman", for_key_path: "manager.name")
137
+ ```
138
+
139
+ Set the value of a key-path (like object assignement, but also work on hashes).
140
+
141
+ For each dot-separated component of the key-path, `value_for_key` is invoked to retrieve the value. On the last component, `set_value(value, for_key:)` is invoked to set the value.
142
+
143
+ If one of the keys doesn't exist, `value_for_undefined_key` is called (which usually results in a `KeyValueCoding::UndefinedKey` exception).
144
+
145
+ ### `Object#value_for_undefined_key(key)`
146
+
147
+ This method is called when a key (or a component in a key path) cannot be found in the target.
148
+
149
+ The default implementation raises an `KeyValueCoding::UndefinedKey` exception. However this method can
150
+ be subclassed to return a default value instead.
151
+
152
+ ## Future work
153
+
154
+ - Allow all objects that respond to dig to return their values
155
+ - Use refinements
156
+ - Implement a more ruby-like method (drill? punch? pierce? scoop? shovel? grub? grab?)
157
+ grab(:companies, :employees, :name)
158
+
159
+ ## Development
160
+
161
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
162
+
163
+ 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).
164
+
165
+ ## Contributing
166
+
167
+ Bug reports and pull requests are welcome on GitHub at https://github.com/kemenaran/key_value_coding. 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/kemenaran/key_value_coding/blob/main/CODE_OF_CONDUCT.md).
168
+
169
+ ## License
170
+
171
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
172
+
173
+ ## Code of Conduct
174
+
175
+ Everyone interacting in the KeyValueCoding project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/key_value_coding/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 "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
data/TODO.md ADDED
File without changes
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Array
4
+ def value_for_key(key)
5
+ map { it.value_for_key(key) }
6
+ end
7
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "debug"
4
+
5
+ class Hash
6
+ # Allow both symbol and strings, for ease of use
7
+ def value_for_key(key)
8
+ if has_key?(key)
9
+ send("[]", key)
10
+ elsif has_key?(key.to_sym)
11
+ send("[]", key.to_sym)
12
+ else
13
+ value_for_undefined_key(key)
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Object
4
+ def self.access_instance_variables_directly? = true
5
+
6
+ def value_for_key(key)
7
+ if respond_to?(key)
8
+ public_send(key)
9
+ elsif self.class.access_instance_variables_directly? && instance_variables.include?(:"@#{key}")
10
+ instance_variable_get(:"@#{key}")
11
+ else
12
+ value_for_undefined_key(key)
13
+ end
14
+ end
15
+
16
+ def values_for_keys(keys)
17
+ keys.map { |k| [k, value_for_key(k)] }.to_h
18
+ end
19
+
20
+ def value_for_key_path(key_path)
21
+ key_path
22
+ .split(".")
23
+ .reduce(self) { |object, key| object.value_for_key(key) }
24
+ end
25
+
26
+ def set_value(value, for_key: nil, for_key_path: nil)
27
+ if for_key
28
+ set_value_for_key(value, for_key)
29
+ elsif for_key_path
30
+ set_value_for_key_path(value, for_key_path)
31
+ else
32
+ raise ArgumentError("Either `for_key` or `for_key_path` must be provided")
33
+ end
34
+ end
35
+
36
+ def set_value_for_key(value, key)
37
+ if respond_to?(:"#{key}=")
38
+ public_send(:"#{key}=", value)
39
+ elsif self.class.access_instance_variables_directly? && instance_variables.include?(:"@#{key}")
40
+ instance_variable_set(:"@#{key}", value)
41
+ else
42
+ set_value_for_undefined_key(value, key)
43
+ end
44
+ end
45
+
46
+ def set_value_for_key_path(value, key_path)
47
+ *path, key = key_path.split(".")
48
+ target = value_for_key_path(path.join('.'))
49
+ target.set_value(value, for_key: key)
50
+ end
51
+
52
+ def value_for_undefined_key(key)
53
+ raise KeyValueCoding::UndefinedKey.new("Undefined key '#{key}' for object #{self}")
54
+ end
55
+
56
+ def set_value_for_undefined_key(value, key)
57
+ raise KeyValueCoding::UndefinedKey.new("Undefined key '#{key}' for object #{self}")
58
+ end
59
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KeyValueCoding
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "key_value_coding/version"
4
+ require_relative "key_value_coding/object"
5
+ require_relative "key_value_coding/array"
6
+ require_relative "key_value_coding/hash"
7
+
8
+ module KeyValueCoding
9
+ class UndefinedKey < StandardError; end
10
+ end
@@ -0,0 +1,4 @@
1
+ module KeyValueCoding
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,57 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: key_value_coding
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Pierre de La Morinerie
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 2026-02-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: This gem exposes `value_for_key` and `set_value(:for_key)` methods, which
13
+ allows traversing a mixed hiearchy of objects, hashes and arrays using a common
14
+ interface.
15
+ email:
16
+ - kemenaran@gmail.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - CHANGELOG.md
22
+ - CODE_OF_CONDUCT.md
23
+ - LICENSE.txt
24
+ - README.md
25
+ - Rakefile
26
+ - TODO.md
27
+ - lib/key_value_coding.rb
28
+ - lib/key_value_coding/array.rb
29
+ - lib/key_value_coding/hash.rb
30
+ - lib/key_value_coding/object.rb
31
+ - lib/key_value_coding/version.rb
32
+ - sig/key_value_coding.rbs
33
+ homepage: https://gitlab.com/pmorinerie/key_value_coding
34
+ licenses:
35
+ - MIT
36
+ metadata:
37
+ homepage_uri: https://gitlab.com/pmorinerie/key_value_coding
38
+ source_code_uri: https://gitlab.com/pmorinerie/key_value_coding
39
+ changelog_uri: https://gitlab.com/pmorinerie/key_value_coding/-/blob/main/CHANGELOG.md
40
+ rdoc_options: []
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: 3.2.0
48
+ required_rubygems_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '0'
53
+ requirements: []
54
+ rubygems_version: 3.6.2
55
+ specification_version: 4
56
+ summary: Port of Cocoa's Key-Value Coding to Ruby
57
+ test_files: []