decoding 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.rspec +3 -0
- data/.rubocop.yml +48 -0
- data/.tool-versions +1 -0
- data/.yardopts +7 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/LICENSE.txt +21 -0
- data/README.md +142 -0
- data/Rakefile +14 -0
- data/lib/decoding/decoder.rb +22 -0
- data/lib/decoding/decoders/and_then.rb +30 -0
- data/lib/decoding/decoders/any.rb +30 -0
- data/lib/decoding/decoders/array.rb +32 -0
- data/lib/decoding/decoders/field.rb +34 -0
- data/lib/decoding/decoders/hash.rb +43 -0
- data/lib/decoding/decoders/index.rb +36 -0
- data/lib/decoding/decoders/map.rb +30 -0
- data/lib/decoding/decoders/match.rb +29 -0
- data/lib/decoding/decoders.rb +224 -0
- data/lib/decoding/result.rb +153 -0
- data/lib/decoding/version.rb +5 -0
- data/lib/decoding.rb +122 -0
- data/sig/decoding.rbs +4 -0
- metadata +70 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 95c32106911949f49f3b50dc46f744912cc9abf75405cd7e20248de3dd0b1668
|
4
|
+
data.tar.gz: 492fbe3bf3d64cfe954da4b7016dabb5287d19d140bbf662146cff678dbe7ca6
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 7ad3271531ef17b985ecacf39e480baa8c117170d6d3d69b0e2bb1f231663f9ad10a41a390e740ff951600dac7f2d7163ac817d3f1928979cea03898249b8a77
|
7
|
+
data.tar.gz: 95b14f9f7bd57df7f537d6c3402b2eafd46ef397686ac343b2239e76732189d606896e26b606838c403436d1738007deee3e51880880f6839ab77308d7d80a90
|
data/.rspec
ADDED
data/.rubocop.yml
ADDED
@@ -0,0 +1,48 @@
|
|
1
|
+
---
|
2
|
+
require:
|
3
|
+
- rubocop-rspec
|
4
|
+
- rubocop-performance
|
5
|
+
- rubocop-rake
|
6
|
+
|
7
|
+
AllCops:
|
8
|
+
TargetRubyVersion: 3.3
|
9
|
+
NewCops: enable
|
10
|
+
|
11
|
+
Style/StringLiterals:
|
12
|
+
Enabled: true
|
13
|
+
EnforcedStyle: double_quotes
|
14
|
+
|
15
|
+
Style/StringLiteralsInInterpolation:
|
16
|
+
Enabled: true
|
17
|
+
EnforcedStyle: double_quotes
|
18
|
+
|
19
|
+
Layout/LineLength:
|
20
|
+
Max: 140
|
21
|
+
|
22
|
+
Metrics/BlockLength:
|
23
|
+
Exclude:
|
24
|
+
- spec/**/*_spec.rb
|
25
|
+
|
26
|
+
Metrics/MethodLength:
|
27
|
+
Max: 17
|
28
|
+
|
29
|
+
Style/SignalException:
|
30
|
+
Enabled: false
|
31
|
+
|
32
|
+
Style/NumberedParametersLimit:
|
33
|
+
Enabled: false
|
34
|
+
|
35
|
+
Style/CaseEquality:
|
36
|
+
Enabled: false
|
37
|
+
|
38
|
+
RSpec/DescribedClass:
|
39
|
+
Enabled: false
|
40
|
+
|
41
|
+
RSpec/MultipleExpectations:
|
42
|
+
Enabled: false
|
43
|
+
|
44
|
+
RSpec/IdenticalEqualityAssertion:
|
45
|
+
Enabled: false
|
46
|
+
|
47
|
+
RSpec/ExampleLength:
|
48
|
+
Enabled: false
|
data/.tool-versions
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
ruby 3.3.0
|
data/.yardopts
ADDED
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -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 arjan@arjanvandergaag.nl. 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/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2024 Arjan van der Gaag
|
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,142 @@
|
|
1
|
+
# Decoding
|
2
|
+
|
3
|
+
Decoding is a library to help transform unknown external data into neat values
|
4
|
+
with known shapes.
|
5
|
+
|
6
|
+
## Installation
|
7
|
+
|
8
|
+
TODO: Replace `decoding` 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.
|
9
|
+
|
10
|
+
Install the gem and add to the application's Gemfile by executing:
|
11
|
+
|
12
|
+
$ bundle add decoding
|
13
|
+
|
14
|
+
If bundler is not being used to manage dependencies, install the gem by executing:
|
15
|
+
|
16
|
+
$ gem install decoding
|
17
|
+
|
18
|
+
## Usage
|
19
|
+
|
20
|
+
Decoding is a library to help transform unknown external data into neat values
|
21
|
+
with known shapes. Consider calling an HTTP API: you might pull in whatever
|
22
|
+
value. After passing it through decoder, you will have a value with a known
|
23
|
+
shape -- or a sensible error message.
|
24
|
+
|
25
|
+
For example, call an API to get some JSON value:
|
26
|
+
|
27
|
+
body = JSON.parse(Net::HTTP.get("https://api.placeholderjson.dev/shipments/7EBWXB5"))
|
28
|
+
|
29
|
+
How do you safely work with `body`? If parsing the response body as JSON has
|
30
|
+
worked, you know you have some kind of Ruby value -- but you're not sure of
|
31
|
+
its structure. This can lead to cryptic error messages far removing of making
|
32
|
+
this HTTP call where values are of unexpected types, hashes turn out not to
|
33
|
+
have certain keys or the nesting of data is different from what you expected.
|
34
|
+
|
35
|
+
Assume the response body, parsed as JSON, results in a value like this:
|
36
|
+
|
37
|
+
{
|
38
|
+
"orderID" => "7EBWXB5",
|
39
|
+
"orderDate" => "1595674680",
|
40
|
+
"estimatedDeliveryDate" => "1596365935",
|
41
|
+
"deliveryDate" => null,
|
42
|
+
"delayed" => false,
|
43
|
+
"status" => {
|
44
|
+
"orderPlaced" => true,
|
45
|
+
"orderShipped" => true,
|
46
|
+
"outForDelivery" => true,
|
47
|
+
"orderDelivered" => false
|
48
|
+
}
|
49
|
+
}
|
50
|
+
|
51
|
+
We can use decoders to extract exactly those pieces from this payload that we need,
|
52
|
+
making assertions along the way of what the data looks like and generating helpful errors
|
53
|
+
when reality does not match our expectations.
|
54
|
+
|
55
|
+
For example, we could parse the above payload like so:
|
56
|
+
|
57
|
+
Order = Data.define(:id, :date, :status)
|
58
|
+
D = Decoding::Decoders
|
59
|
+
order_decoder = D.map(
|
60
|
+
D.field("orderID", D.string),
|
61
|
+
D.map(D.field("orderDate", D.string)) { Time.at(_1.to_i) },
|
62
|
+
D.hash(D.string, D.boolean)
|
63
|
+
) { Order.new(*args) }
|
64
|
+
Decoding.decode(order_decoder, body)
|
65
|
+
# => Decoding::Ok(#<data Order
|
66
|
+
id: '7EBWXB5',
|
67
|
+
date: 2020-07-25 12:58:00 +0200,
|
68
|
+
status: {"orderPlaced"=>true,"orderShipped"=>true,"outForDelivery"=>true,"orderDelivered"=>false}>)
|
69
|
+
|
70
|
+
Decoders take an input value and generate an output value from it. There are
|
71
|
+
decoders for basic Ruby types, compound types such as arrays and hashes,
|
72
|
+
decoders for trying out various decoders and, finally, there is the `map`
|
73
|
+
decoder for decoding one or more output values from a given input value and
|
74
|
+
applying a transformation to them with a block. All these decoders can be
|
75
|
+
composed together into new, more complex decoders.
|
76
|
+
|
77
|
+
A decoder is, in essence, a function that returns a result based on an input value. Consider
|
78
|
+
how, roughly, the `string` decoder is implemented:
|
79
|
+
|
80
|
+
string_decoder = ->(input_value) do
|
81
|
+
if input_value.is_a?(String)
|
82
|
+
Decoding::Result.ok(input_value)
|
83
|
+
else
|
84
|
+
Decoding::Result.err("expected String, got #{input_value.class}")
|
85
|
+
end
|
86
|
+
end
|
87
|
+
|
88
|
+
You can use the base decoders along with `map` to write more complex decoder. For example, you could
|
89
|
+
extract a `time_decoder` from the example above:
|
90
|
+
|
91
|
+
time_decoder = D.map(D.string) { Time.at(_1.to_i) }
|
92
|
+
|
93
|
+
When the shape of the incoming data is unknown, you can try out various
|
94
|
+
decoders in a row to find the first that succeeds using `any`:
|
95
|
+
|
96
|
+
string_or_integer = D.any(D.string, D.integer)
|
97
|
+
Decoding.decode(string_or_integer, 1) # => Decoding::Ok(1)
|
98
|
+
Decoding.decode(string_or_integer, '1') # => Decoding::Ok('1')
|
99
|
+
|
100
|
+
You can also base one decoder on a previously decoded value. For example, a
|
101
|
+
payload might contain a version number describing its format. Use `and_then`
|
102
|
+
to decode one value and then construct a new decoder to run against the same
|
103
|
+
input using that value:
|
104
|
+
|
105
|
+
multiple_version_decoder = D.and_then(D.field("version", D.string)) do |version|
|
106
|
+
if version == "1"
|
107
|
+
D.field("name", D.string)
|
108
|
+
else
|
109
|
+
D.field("fullName", D.string)
|
110
|
+
end
|
111
|
+
end
|
112
|
+
|
113
|
+
Now, you have a decoder that can work inputs using format version 1 and 2:
|
114
|
+
|
115
|
+
Decoding.decode(multiple_version_decoder, "version" => "1", "name" => "John")
|
116
|
+
# => "John"
|
117
|
+
Decoding.decode(multiple_version_decoder, "version" => "2", "fullName" => "Paul")
|
118
|
+
# => "Paul"
|
119
|
+
|
120
|
+
The return values of decoding are `Decoding::Result` values, which come in
|
121
|
+
`Ok` and `Err` subclasses. These describe how the decoding either succeeded or
|
122
|
+
failed. The `Ok` values contain the decoded result, while the `Err` values
|
123
|
+
always contain a string error message. It is up to you, as a developer, to
|
124
|
+
decide how to deal with unsuccessful decoding.
|
125
|
+
|
126
|
+
## Development
|
127
|
+
|
128
|
+
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.
|
129
|
+
|
130
|
+
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).
|
131
|
+
|
132
|
+
## Contributing
|
133
|
+
|
134
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/avdgaag/decoding. 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/avdgaag/decoding/blob/main/CODE_OF_CONDUCT.md).
|
135
|
+
|
136
|
+
## License
|
137
|
+
|
138
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
139
|
+
|
140
|
+
## Code of Conduct
|
141
|
+
|
142
|
+
Everyone interacting in the Decoding project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/avdgaag/decoding/blob/main/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
@@ -0,0 +1,14 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "bundler/gem_tasks"
|
4
|
+
require "rspec/core/rake_task"
|
5
|
+
require "yard"
|
6
|
+
require "rubocop/rake_task"
|
7
|
+
|
8
|
+
RSpec::Core::RakeTask.new(:spec)
|
9
|
+
|
10
|
+
RuboCop::RakeTask.new
|
11
|
+
|
12
|
+
YARD::Rake::YardocTask.new
|
13
|
+
|
14
|
+
task default: %i[spec rubocop yard]
|
@@ -0,0 +1,22 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "forwardable"
|
4
|
+
require_relative "result"
|
5
|
+
|
6
|
+
module Decoding
|
7
|
+
# A decoder is a callable object that reads any input value and returns an
|
8
|
+
# optionally transformed value.
|
9
|
+
#
|
10
|
+
# @abstract
|
11
|
+
class Decoder
|
12
|
+
extend Forwardable
|
13
|
+
def_delegators "Decoding::Result", :all, :ok, :err
|
14
|
+
|
15
|
+
# @param value [Object]
|
16
|
+
# @return [Decoding::Result<Object>]
|
17
|
+
def call(value); end
|
18
|
+
|
19
|
+
# @return [Decoding::Decoder<a>]
|
20
|
+
def to_decoder = self
|
21
|
+
end
|
22
|
+
end
|
@@ -0,0 +1,30 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "../decoder"
|
4
|
+
|
5
|
+
module Decoding
|
6
|
+
module Decoders
|
7
|
+
# Create a decoder that depends on a previously decoded value.
|
8
|
+
#
|
9
|
+
# @see Decoding::Decoders.and_then
|
10
|
+
class AndThen < Decoder
|
11
|
+
# @param decoder [Decoding::Decoder<a>]
|
12
|
+
# @yieldparam [a]
|
13
|
+
# @yieldreturn [Decoding::Decoder<b>]
|
14
|
+
# @return [Decoding::Decoder<b>]
|
15
|
+
def initialize(decoder, &block)
|
16
|
+
@decoder = decoder.to_decoder
|
17
|
+
@block = block
|
18
|
+
super()
|
19
|
+
end
|
20
|
+
|
21
|
+
# @param value [Object]
|
22
|
+
# @return [Decoding::Result<b>]
|
23
|
+
def call(value)
|
24
|
+
@decoder.call(value).and_then do |decoded_value|
|
25
|
+
@block.call(decoded_value).call(value)
|
26
|
+
end
|
27
|
+
end
|
28
|
+
end
|
29
|
+
end
|
30
|
+
end
|
@@ -0,0 +1,30 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "../result"
|
4
|
+
require_relative "../decoder"
|
5
|
+
|
6
|
+
module Decoding
|
7
|
+
module Decoders
|
8
|
+
# A decoder wrapping any number of decoders, finding the first one that
|
9
|
+
# matches the given value and returning its result.
|
10
|
+
#
|
11
|
+
# @see Decoding::Decoders.any
|
12
|
+
class Any < Decoder
|
13
|
+
# @private
|
14
|
+
Err = Result.err("None of the decoders matched")
|
15
|
+
|
16
|
+
# @param decoder [Decoding::Decoder<Object>]
|
17
|
+
# @param decoders [Decoding::Decoder<Object>]
|
18
|
+
def initialize(decoder, *decoders)
|
19
|
+
@decoders = [decoder, *decoders].map(&:to_decoder)
|
20
|
+
super()
|
21
|
+
end
|
22
|
+
|
23
|
+
# @param value [Object]
|
24
|
+
# @return [Decoding::Result<Object>]
|
25
|
+
def call(value)
|
26
|
+
@decoders.lazy.map { _1.call(value) }.find(-> { Err }, &:ok?)
|
27
|
+
end
|
28
|
+
end
|
29
|
+
end
|
30
|
+
end
|
@@ -0,0 +1,32 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "../result"
|
4
|
+
require_relative "../decoder"
|
5
|
+
|
6
|
+
module Decoding
|
7
|
+
module Decoders
|
8
|
+
# Decode an array where all values match a given decoder.
|
9
|
+
#
|
10
|
+
# @see Decoding::Decoders.array
|
11
|
+
class Array < Decoder
|
12
|
+
# @param decoder [Decoding::Decoder<a>]
|
13
|
+
def initialize(decoder)
|
14
|
+
@decoder = decoder.to_decoder
|
15
|
+
super()
|
16
|
+
end
|
17
|
+
|
18
|
+
# @param value [Object]
|
19
|
+
# @return [Decoding::Result<a>]
|
20
|
+
def call(value)
|
21
|
+
if value.is_a?(::Array)
|
22
|
+
value
|
23
|
+
.each_with_index
|
24
|
+
.map { |v, i| @decoder.call(v).map_err { |e| "error decoding array item #{i}: #{e}" } }
|
25
|
+
.then { all _1 }
|
26
|
+
else
|
27
|
+
err("expected an Array, got: #{value.class}")
|
28
|
+
end
|
29
|
+
end
|
30
|
+
end
|
31
|
+
end
|
32
|
+
end
|
@@ -0,0 +1,34 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "../decoder"
|
4
|
+
|
5
|
+
module Decoding
|
6
|
+
module Decoders
|
7
|
+
# Decode a value from key in a given hash.
|
8
|
+
#
|
9
|
+
# @see Decoding::Decoders.field
|
10
|
+
class Field < Decoder
|
11
|
+
# @param key [Object]
|
12
|
+
# @param decoder [Decoding::Decoder<a>]
|
13
|
+
def initialize(key, decoder)
|
14
|
+
@key = key.to_str
|
15
|
+
@decoder = decoder.to_decoder
|
16
|
+
super()
|
17
|
+
end
|
18
|
+
|
19
|
+
# @param value [Object]
|
20
|
+
# @return [Deceoding::Result<a>]
|
21
|
+
def call(value)
|
22
|
+
if value.is_a?(::Hash)
|
23
|
+
if value.key?(@key)
|
24
|
+
@decoder.call(value.fetch(@key))
|
25
|
+
else
|
26
|
+
err("expected a Hash with key #{@key}")
|
27
|
+
end
|
28
|
+
else
|
29
|
+
err("expected a Hash, got: #{value.inspect}")
|
30
|
+
end
|
31
|
+
end
|
32
|
+
end
|
33
|
+
end
|
34
|
+
end
|
@@ -0,0 +1,43 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "../decoder"
|
4
|
+
|
5
|
+
module Decoding
|
6
|
+
module Decoders
|
7
|
+
# Decode an arbitrary hash using decoders for keys and values.
|
8
|
+
#
|
9
|
+
# @see Decoding::Decoders.hash
|
10
|
+
class Hash < Decoder
|
11
|
+
# @param key_decoder [Decoding::Decoder<a>]
|
12
|
+
# @param value_decoder [Decoding::Decoder<b>]
|
13
|
+
def initialize(key_decoder, value_decoder)
|
14
|
+
@key_decoder = key_decoder.to_decoder
|
15
|
+
@value_decoder = value_decoder.to_decoder
|
16
|
+
super()
|
17
|
+
end
|
18
|
+
|
19
|
+
# @param value [Object]
|
20
|
+
# @return [Decoding::Result<Hash<a, b>>]
|
21
|
+
def call(value)
|
22
|
+
if value.is_a?(::Hash)
|
23
|
+
key_value_pairs = value.map do |k, v|
|
24
|
+
all(
|
25
|
+
[
|
26
|
+
@key_decoder
|
27
|
+
.call(k)
|
28
|
+
.map_err { |e| "error decoding key #{k.inspect}: #{e}" },
|
29
|
+
|
30
|
+
@value_decoder
|
31
|
+
.call(v)
|
32
|
+
.map_err { |e| "error decoding value for key #{k.inspect}: #{e}" }
|
33
|
+
]
|
34
|
+
)
|
35
|
+
end
|
36
|
+
all(key_value_pairs).map(&:to_h)
|
37
|
+
else
|
38
|
+
err("expected Hash, got #{value.class}")
|
39
|
+
end
|
40
|
+
end
|
41
|
+
end
|
42
|
+
end
|
43
|
+
end
|
@@ -0,0 +1,36 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "../result"
|
4
|
+
require_relative "../decoder"
|
5
|
+
|
6
|
+
module Decoding
|
7
|
+
module Decoders
|
8
|
+
# Decode the element at a specific offset in an array.
|
9
|
+
#
|
10
|
+
# @see Decoding::Decoders.index
|
11
|
+
class Index < Decoder
|
12
|
+
# @private
|
13
|
+
Err = Result.err("error decoding array: index is out of bounds")
|
14
|
+
|
15
|
+
# @param index [Integer]
|
16
|
+
# @param decoder [Decoding::Decoder<Object>]
|
17
|
+
def initialize(index, decoder)
|
18
|
+
@index = index.to_int
|
19
|
+
@decoder = decoder.to_decoder
|
20
|
+
super()
|
21
|
+
end
|
22
|
+
|
23
|
+
# @param value [Object]
|
24
|
+
# @return [Decoding::Decoder<Object>]
|
25
|
+
def call(value)
|
26
|
+
return err("expected an Array, got: #{value.class}") unless value.is_a?(::Array)
|
27
|
+
|
28
|
+
@decoder
|
29
|
+
.call(value.fetch(@index))
|
30
|
+
.map_err { "error decoding array item #{@index}: #{_1}" }
|
31
|
+
rescue IndexError => e
|
32
|
+
err("error decoding array: #{e}")
|
33
|
+
end
|
34
|
+
end
|
35
|
+
end
|
36
|
+
end
|
@@ -0,0 +1,30 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "../decoder"
|
4
|
+
|
5
|
+
module Decoding
|
6
|
+
module Decoders
|
7
|
+
# A decoder that decodes a value and then applies a transformation to it, if
|
8
|
+
# successful.
|
9
|
+
#
|
10
|
+
# @see Decoding::Decoders.map
|
11
|
+
class Map < Decoder
|
12
|
+
# @param decoder [Decoding::Decoder<a>]
|
13
|
+
# @yieldparam value [a]
|
14
|
+
# @yieldreturn [b]
|
15
|
+
def initialize(decoder, *rest, &block)
|
16
|
+
@decoders = [decoder, *rest].map(&:to_decoder)
|
17
|
+
@block = block
|
18
|
+
super()
|
19
|
+
end
|
20
|
+
|
21
|
+
# @param value [Object]
|
22
|
+
# @return [Decoding::Result<b>]
|
23
|
+
def call(value)
|
24
|
+
Result
|
25
|
+
.all(@decoders.map { _1.call(value) })
|
26
|
+
.map { @block.call(*_1) }
|
27
|
+
end
|
28
|
+
end
|
29
|
+
end
|
30
|
+
end
|
@@ -0,0 +1,29 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "../decoder"
|
4
|
+
|
5
|
+
module Decoding
|
6
|
+
module Decoders
|
7
|
+
# Decoder that matches values using the `===` operator. This will work with
|
8
|
+
# regular expressions or classes.
|
9
|
+
class Match < Decoder
|
10
|
+
# @param pattern [#===]
|
11
|
+
def initialize(pattern)
|
12
|
+
@pattern = pattern
|
13
|
+
super()
|
14
|
+
end
|
15
|
+
|
16
|
+
# @param value [Object]
|
17
|
+
# @return [Decoding::Result<a>]
|
18
|
+
def call(value)
|
19
|
+
if @pattern === value
|
20
|
+
ok(value)
|
21
|
+
elsif @pattern.is_a?(Class)
|
22
|
+
err("expected #{@pattern}, got #{value.class}")
|
23
|
+
else
|
24
|
+
err("expected value matching #{@pattern.inspect}, got: #{value.inspect}")
|
25
|
+
end
|
26
|
+
end
|
27
|
+
end
|
28
|
+
end
|
29
|
+
end
|
@@ -0,0 +1,224 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "decoders/match"
|
4
|
+
require_relative "decoders/map"
|
5
|
+
require_relative "decoders/any"
|
6
|
+
require_relative "decoders/field"
|
7
|
+
require_relative "decoders/array"
|
8
|
+
require_relative "decoders/index"
|
9
|
+
require_relative "decoders/hash"
|
10
|
+
require_relative "decoders/and_then"
|
11
|
+
require_relative "result"
|
12
|
+
|
13
|
+
module Decoding
|
14
|
+
# Decoders are composable functions for deconstructing unknown input values
|
15
|
+
# into known output values.
|
16
|
+
module Decoders
|
17
|
+
module_function
|
18
|
+
|
19
|
+
# @!group Simple decoders
|
20
|
+
|
21
|
+
# Decode any string value.
|
22
|
+
#
|
23
|
+
# @example
|
24
|
+
# decode(string, "foo") # => Decoding::Ok("foo")
|
25
|
+
# @return [Decoding::Decoder<String>]
|
26
|
+
# @see Decoding::Decoders::Match
|
27
|
+
def string = Decoders::Match.new(String)
|
28
|
+
|
29
|
+
# Decode any integer value.
|
30
|
+
#
|
31
|
+
# @example
|
32
|
+
# decode(integer, 1) # => Decoding::Ok(1)
|
33
|
+
# @return [Decoding::Decoder<Integer>]
|
34
|
+
# @see Decoding::Decoders::Match
|
35
|
+
def integer = Decoders::Match.new(Integer)
|
36
|
+
|
37
|
+
# Decode any float value.
|
38
|
+
#
|
39
|
+
# @example
|
40
|
+
# decode(float, 0.5) # => Decoding::Ok(0.5)
|
41
|
+
# @return [Decoding::Decoder<Float>]
|
42
|
+
# @see Decoding::Decoders::Match
|
43
|
+
def float = Decoders::Match.new(Float)
|
44
|
+
|
45
|
+
# Decode any numeric value (includes both integers and floats).
|
46
|
+
#
|
47
|
+
# @example
|
48
|
+
# decode(numeric, 1) # => Decoding::Ok(1)
|
49
|
+
# decode(numeric, 1.5) # => Decoding::Ok(1.5)
|
50
|
+
# @return [Decoding::Decoder<Numeric>]
|
51
|
+
# @see Decoding::Decoders::Match
|
52
|
+
def numeric = Decoders::Match.new(Numeric)
|
53
|
+
|
54
|
+
# Decode a `nil` value.
|
55
|
+
#
|
56
|
+
# @example
|
57
|
+
# decode(Decoders.nil, nil) # => Decoding::Ok(nil)
|
58
|
+
# @return [Decoding::Decoder<NilClass>]
|
59
|
+
# @see Decoding::Decoders::Match
|
60
|
+
def nil = Decoders::Match.new(NilClass)
|
61
|
+
|
62
|
+
# Decode a `true` value.
|
63
|
+
#
|
64
|
+
# @example
|
65
|
+
# decode(Decoding.true, true) # => Decoding::Ok(true)
|
66
|
+
# @return [Decoding::Decoder<TrueClass>]
|
67
|
+
# @see Decoding::Decoders::Match
|
68
|
+
def true = Decoders::Match.new(TrueClass)
|
69
|
+
|
70
|
+
# Decode a `false` value.
|
71
|
+
#
|
72
|
+
# @example
|
73
|
+
# decode(Decoders.false, false) # => Decoding::Ok(false)
|
74
|
+
# @return [Decoding::Decoder<FalseClass>]
|
75
|
+
# @see Decoding::Decoders::Match
|
76
|
+
def false = Decoders::Match.new(FalseClass)
|
77
|
+
|
78
|
+
# Decode a boolean value (either `true` or `false`).
|
79
|
+
#
|
80
|
+
# @example
|
81
|
+
# decode(boolean, true) # => Decoding::Ok(true)
|
82
|
+
# decode(boolean, false) # => Decoding::Ok(false)
|
83
|
+
# @return [Decoding::Decoder<Boolean>]
|
84
|
+
def boolean = any(self.true, self.false)
|
85
|
+
|
86
|
+
# Decode a String value into a symbol.
|
87
|
+
#
|
88
|
+
# @example
|
89
|
+
# decode(symbol, "foo") # => Decoding::Ok(:foo)
|
90
|
+
# @return [Decoding::Decoder<Symbol>]
|
91
|
+
def symbol = map(string, &:to_sym)
|
92
|
+
|
93
|
+
# @!group Utility decoders
|
94
|
+
|
95
|
+
# A decoder that always succeeds with the given value.
|
96
|
+
#
|
97
|
+
# @example
|
98
|
+
# decode(succeed(5), "foo") # => Decoding::Ok(5)
|
99
|
+
# @return [Decoding::Decoder<String>]
|
100
|
+
def succeed(value) = ->(_) { Result.ok(value) }
|
101
|
+
|
102
|
+
# A decoder that always fails with the given value.
|
103
|
+
#
|
104
|
+
# @example
|
105
|
+
# decode(fail("oh no"), "foo") # => Decoding::Err("oh no")
|
106
|
+
# @return [Decoding::Decoder<String>]
|
107
|
+
def fail(value) = ->(_) { Result.err(value) }
|
108
|
+
|
109
|
+
# @!group Compound decoders
|
110
|
+
|
111
|
+
# Decode a value with the given decoder and, if successful, apply a block to
|
112
|
+
# the decoded result.
|
113
|
+
#
|
114
|
+
# Given multiple decoders, apply them all to the same value and, if all
|
115
|
+
# succeeded, create a single output value from them.
|
116
|
+
#
|
117
|
+
# @example map over a single value
|
118
|
+
# decode(map(string, &:upcase), "foo") # => Decoding::Ok("FOO")
|
119
|
+
# @example map over multiple values
|
120
|
+
# decode(
|
121
|
+
# map(
|
122
|
+
# field("id", integer),
|
123
|
+
# field("name", string)
|
124
|
+
# ) { |id, name| [id, name] },
|
125
|
+
# { "id" => 1, "name" => "john" }
|
126
|
+
# )
|
127
|
+
# # => [1, "john"]
|
128
|
+
# @overload map(decoder, *decoders)
|
129
|
+
# @param decoder [Decoding::Decoder<a>]
|
130
|
+
# @yieldparam value [a]
|
131
|
+
# @yieldreturn [b]
|
132
|
+
# @return [Decoding::Decoder<b>]
|
133
|
+
# @see Decoding::Decoders::Map
|
134
|
+
def map(...) = Decoders::Map.new(...)
|
135
|
+
|
136
|
+
# Decode a value by trying many different decoders in order, using the first
|
137
|
+
# matching result -- or a failure when none of the given decoders succeed.
|
138
|
+
#
|
139
|
+
# @example
|
140
|
+
# decode(any(string, integer), 12) # => Decoding::Ok(12)
|
141
|
+
# decode(any(string, integer), '12') # => Decoding::Ok('12')
|
142
|
+
# @overload any(decoder, *decoders)
|
143
|
+
# @param decoder [Decoding::Decoder<a>]
|
144
|
+
# @return [Decoding::Decoder<a>]
|
145
|
+
# @see Decoding::Decoders::Any
|
146
|
+
def any(...) = Decoders::Any.new(...)
|
147
|
+
|
148
|
+
# Decode a value that may or may not be `nil`.
|
149
|
+
#
|
150
|
+
# @example
|
151
|
+
# decode(string, "foo") # => Decoding::Ok("foo")
|
152
|
+
# decode(string, nil) # => Decoding::Ok(nil)
|
153
|
+
# @param decoder [Decoding::Decoder<a>]
|
154
|
+
# @return [Decoding::Decoder<a, nil>]
|
155
|
+
def optional(decoder) = any(decoder, self.nil)
|
156
|
+
|
157
|
+
# Decode a value from a given key in a hash.
|
158
|
+
#
|
159
|
+
# @example
|
160
|
+
# decode(field('id', integer), { 'id' => 5 }) # => Decoding::Ok(5)
|
161
|
+
# @overload field(key, decoder)
|
162
|
+
# @param key [Object]
|
163
|
+
# @param decoder [Decoding::Decoder<a>]
|
164
|
+
# @return [Decoding::Decoder<a>]
|
165
|
+
# @see Decoding::Decoders::Field
|
166
|
+
def field(...) = Decoders::Field.new(...)
|
167
|
+
|
168
|
+
# Decode an array of values using a given decoder.
|
169
|
+
#
|
170
|
+
# @example
|
171
|
+
# decode(array(integer), [1, 2, 3]) # => Decoding::Ok([1, 2, 3])
|
172
|
+
# @overload array(decoder)
|
173
|
+
# @param decoder [Decoding::Decoder<a>]
|
174
|
+
# @return [Decoding::Decoder<Array<a>>]
|
175
|
+
# @see Decoding::Decoders::Array
|
176
|
+
def array(...) = Decoders::Array.new(...)
|
177
|
+
|
178
|
+
# Decode an array element by index using a given decoder.
|
179
|
+
#
|
180
|
+
# @example
|
181
|
+
# decode(index(0, integer), [1, 2, 3]) # => Decoding::Ok(1)
|
182
|
+
# @overload index(integer, decoder)
|
183
|
+
# @param index [Integer]
|
184
|
+
# @param decoder [Decoding::Decoder<a>]
|
185
|
+
# @return [Decoding::Decoder<a>]
|
186
|
+
# @see Decoding::Decoders::Index
|
187
|
+
def index(...) = Decoders::Index.new(...)
|
188
|
+
|
189
|
+
# Decode a Hash with arbitrary contents using two decoders for the keys and
|
190
|
+
# the pairs.
|
191
|
+
#
|
192
|
+
# @example
|
193
|
+
# decode(hash(string, integer), { 'john' => 1 })
|
194
|
+
# # => Decoding::Ok({ 'john' => 1 })
|
195
|
+
# @overload hash(key_decoder, value_decoder)
|
196
|
+
# @param key_decoder [Decoding::Decoder<a>]
|
197
|
+
# @param value_decoder [Decoding::Decoder<b>]
|
198
|
+
# @return [Decoding::Decoder<Hash<a, b>>]
|
199
|
+
# @see Decoding::Decoders::Hash
|
200
|
+
def hash(...) = Decoders::Hash.new(...)
|
201
|
+
|
202
|
+
# Create a decoder that depends on a previously decoded value.
|
203
|
+
#
|
204
|
+
# @example
|
205
|
+
# decoder = and_then(field("version", integer)) do |version|
|
206
|
+
# if version == 1
|
207
|
+
# field("name", string)
|
208
|
+
# else
|
209
|
+
# field("fullName", string)
|
210
|
+
# end
|
211
|
+
# end
|
212
|
+
# decode(decoder, { "version" => 1, "name" => "john" })
|
213
|
+
# # => Decoding::Ok("john")
|
214
|
+
# decode(decoder, { "version" => 2, "fullName" => "john" })
|
215
|
+
# # => Decoding::Ok("john")
|
216
|
+
# @overload and_then(deocder)
|
217
|
+
# @param decoder [Decoding::Decoder<a>]
|
218
|
+
# @yieldparam value [a]
|
219
|
+
# @yieldreturn [Decoding::Decoder<b>]
|
220
|
+
# @return [Decoding::Decoder<b>]
|
221
|
+
# @see Decoding::Decoders::AndThen
|
222
|
+
def and_then(...) = Decoders::AndThen.new(...)
|
223
|
+
end
|
224
|
+
end
|
@@ -0,0 +1,153 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Decoding
|
4
|
+
# A result represent the outcome of some computation that can succeed or fail.
|
5
|
+
# The results are represented with two subclasses of `Result`: `Ok` and `Err`.
|
6
|
+
# Each hold a single result value.
|
7
|
+
#
|
8
|
+
# The use of a result is the common interface provided to callers for
|
9
|
+
# transforming or chaining result values.
|
10
|
+
#
|
11
|
+
# @abstract
|
12
|
+
class Result
|
13
|
+
# Construct a new `Ok` value with the given `value`.
|
14
|
+
#
|
15
|
+
# @param value [a]
|
16
|
+
# @return [Decoding::Ok<a>]
|
17
|
+
def self.ok(value) = Ok.new(value)
|
18
|
+
|
19
|
+
# Construct a new `Err` value with the given `value`.
|
20
|
+
#
|
21
|
+
# @param value [a]
|
22
|
+
# @return [Decoding::Err<a>]
|
23
|
+
def self.err(value) = Err.new(value)
|
24
|
+
|
25
|
+
# Collapse array of result values into a single result, or return the
|
26
|
+
# first `Err` value.
|
27
|
+
#
|
28
|
+
# @example
|
29
|
+
# all(Ok(1), Ok(2)) # => Ok([1, 2])
|
30
|
+
# all(Ok(1), Err("error")) # => Err("error")
|
31
|
+
# @param results [Array<Result<a>>]
|
32
|
+
# @return [Result<a>]
|
33
|
+
def self.all(results)
|
34
|
+
results.reduce(ok([])) do |acc, el|
|
35
|
+
acc.and(el.to_result) { [*_1, _2] }
|
36
|
+
end
|
37
|
+
end
|
38
|
+
|
39
|
+
private_class_method :new
|
40
|
+
|
41
|
+
# @return [Object]
|
42
|
+
attr_reader :value
|
43
|
+
|
44
|
+
protected :value
|
45
|
+
|
46
|
+
# @private
|
47
|
+
attr_reader :hash
|
48
|
+
|
49
|
+
def initialize(value)
|
50
|
+
@value = value
|
51
|
+
@hash = [self.class, value].hash
|
52
|
+
freeze
|
53
|
+
end
|
54
|
+
|
55
|
+
def eql?(other)
|
56
|
+
other.is_a?(self.class) && value == other.value
|
57
|
+
end
|
58
|
+
alias == eql?
|
59
|
+
|
60
|
+
def inspect
|
61
|
+
"#<#{self.class} #{value.inspect}>"
|
62
|
+
end
|
63
|
+
|
64
|
+
# Whether this value is an `Ok` value.
|
65
|
+
#
|
66
|
+
# @return [Boolean]
|
67
|
+
def ok? = false
|
68
|
+
|
69
|
+
# Whether this value is an `Err` value.
|
70
|
+
#
|
71
|
+
# @return [Boolean]
|
72
|
+
def err? = false
|
73
|
+
|
74
|
+
# Extract the value out of a `Result` value. In case of an `Ok`, this
|
75
|
+
# returns the result's value. In case of an `Err`, the given `default_value`
|
76
|
+
# is returned.
|
77
|
+
#
|
78
|
+
# @param default_value [Object]
|
79
|
+
# @return [Object]
|
80
|
+
def unwrap(default_value) = default_value
|
81
|
+
|
82
|
+
# Create a new `Result` value for the result of the block applied to this
|
83
|
+
# result's `value`. `Err` values are returned as-is.
|
84
|
+
#
|
85
|
+
# @example
|
86
|
+
# Result.ok(123).map { |i| i * 2 } # => Ok(246)
|
87
|
+
# Result.err("error").map { |i| i * 2 } # => Err("error")
|
88
|
+
# @yieldparam value [a]
|
89
|
+
# @yieldreturn [b]
|
90
|
+
# @return [Decoding::Result<b>]
|
91
|
+
def map = self
|
92
|
+
|
93
|
+
# Create a new `Result` value for the result of the block applied to this
|
94
|
+
# result's `value`. `Ok` values are returned as-is.
|
95
|
+
#
|
96
|
+
# @example
|
97
|
+
# Result.ok(123).map { |s| s.upcase } # => Ok(123)
|
98
|
+
# Result.err("error").map { |s| s.upcase } # => Err("ERROR")
|
99
|
+
# @yieldparam value [a]
|
100
|
+
# @yieldreturn [b]
|
101
|
+
# @return [Decoding::Result<b>]
|
102
|
+
def map_err = self
|
103
|
+
|
104
|
+
# Combine two `Result` values if they are both `Ok` using the given block, or
|
105
|
+
# return the first `Err` value.
|
106
|
+
#
|
107
|
+
# @overload and(other)
|
108
|
+
# @param other [Decoding::Result<a>]
|
109
|
+
# @yieldparam left [Object]
|
110
|
+
# @yieldparam right [Object]
|
111
|
+
# @yieldreturn [c]
|
112
|
+
# @return [Decoding::Result<c>]
|
113
|
+
def and(_) = self
|
114
|
+
|
115
|
+
# Transform a result using a block that will also return a result.
|
116
|
+
#
|
117
|
+
# @yieldparam value [Object]
|
118
|
+
# @yieldreturn [Decoding::Result<a>]
|
119
|
+
# @return [Decoding::Result<a>]
|
120
|
+
def and_then = self
|
121
|
+
|
122
|
+
def to_result = self
|
123
|
+
end
|
124
|
+
|
125
|
+
# The `Ok` value represents the result of a successful computation.
|
126
|
+
#
|
127
|
+
# @see Decoding::Err
|
128
|
+
class Ok < Result
|
129
|
+
public_class_method :new
|
130
|
+
|
131
|
+
def ok? = true
|
132
|
+
def unwrap(_) = value
|
133
|
+
def map = self.class.new(yield value)
|
134
|
+
|
135
|
+
def and(other)
|
136
|
+
return other unless other.is_a?(self.class)
|
137
|
+
|
138
|
+
self.class.new(yield value, other.value)
|
139
|
+
end
|
140
|
+
|
141
|
+
def and_then = yield(value).to_result
|
142
|
+
end
|
143
|
+
|
144
|
+
# The `Err` value represents the result of an unsuccessful computation.
|
145
|
+
#
|
146
|
+
# @see Decoding::Err
|
147
|
+
class Err < Result
|
148
|
+
public_class_method :new
|
149
|
+
|
150
|
+
def err? = true
|
151
|
+
def map_err = self.class.new(yield value)
|
152
|
+
end
|
153
|
+
end
|
data/lib/decoding.rb
ADDED
@@ -0,0 +1,122 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "decoding/version"
|
4
|
+
require_relative "decoding/decoders"
|
5
|
+
|
6
|
+
# Decoding is a library to help transform unknown external data into neat values
|
7
|
+
# with known shapes. Consider calling an HTTP API: you might pull in whatever
|
8
|
+
# value. After passing it through decoder, you will have a value with a known
|
9
|
+
# shape -- or a sensible error message.
|
10
|
+
#
|
11
|
+
# For example, call an API to get some JSON value:
|
12
|
+
#
|
13
|
+
# body = JSON.parse(Net::HTTP.get("https://api.placeholderjson.dev/shipments/7EBWXB5"))
|
14
|
+
#
|
15
|
+
# How do you safely work with `body`? If parsing the response body as JSON has
|
16
|
+
# worked, you know you have some kind of Ruby value -- but you're not sure of
|
17
|
+
# its structure. This can lead to cryptic error messages far removing of making
|
18
|
+
# this HTTP call where values are of unexpected types, hashes turn out not to
|
19
|
+
# have certain keys or the nesting of data is different from what you expected.
|
20
|
+
#
|
21
|
+
# Assume the response body, parsed as JSON, results in a value like this:
|
22
|
+
#
|
23
|
+
# {
|
24
|
+
# "orderID" => "7EBWXB5",
|
25
|
+
# "orderDate" => "1595674680",
|
26
|
+
# "estimatedDeliveryDate" => "1596365935",
|
27
|
+
# "deliveryDate" => null,
|
28
|
+
# "delayed" => false,
|
29
|
+
# "status" => {
|
30
|
+
# "orderPlaced" => true,
|
31
|
+
# "orderShipped" => true,
|
32
|
+
# "outForDelivery" => true,
|
33
|
+
# "orderDelivered" => false
|
34
|
+
# }
|
35
|
+
# }
|
36
|
+
#
|
37
|
+
# We can use decoders to extract exactly those pieces from this payload that we need,
|
38
|
+
# making assertions along the way of what the data looks like and generating helpful errors
|
39
|
+
# when reality does not match our expectations.
|
40
|
+
#
|
41
|
+
# For example, we could parse the above payload like so:
|
42
|
+
#
|
43
|
+
# Order = Data.define(:id, :date, :status)
|
44
|
+
# D = Decoding::Decoders
|
45
|
+
# order_decoder = D.map(
|
46
|
+
# D.field("orderID", D.string),
|
47
|
+
# D.map(D.field("orderDate", D.string)) { Time.at(_1.to_i) },
|
48
|
+
# D.hash(D.string, D.boolean)
|
49
|
+
# ) { Order.new(*args) }
|
50
|
+
# Decoding.decode(order_decoder, body)
|
51
|
+
# # => Decoding::Ok(#<data Order
|
52
|
+
# id: '7EBWXB5',
|
53
|
+
# date: 2020-07-25 12:58:00 +0200,
|
54
|
+
# status: {"orderPlaced"=>true,"orderShipped"=>true,"outForDelivery"=>true,"orderDelivered"=>false}>)
|
55
|
+
#
|
56
|
+
# Decoders take an input value and generate an output value from it. There are
|
57
|
+
# decoders for basic Ruby types, compound types such as arrays and hashes,
|
58
|
+
# decoders for trying out various decoders and, finally, there is the `map`
|
59
|
+
# decoder for decoding one or more output values from a given input value and
|
60
|
+
# applying a transformation to them with a block. All these decoders can be
|
61
|
+
# composed together into new, more complex decoders.
|
62
|
+
#
|
63
|
+
# A decoder is, in essence, a function that returns a result based on an input value. Consider
|
64
|
+
# how, roughly, the `string` decoder is implemented:
|
65
|
+
#
|
66
|
+
# string_decoder = ->(input_value) do
|
67
|
+
# if input_value.is_a?(String)
|
68
|
+
# Decoding::Result.ok(input_value)
|
69
|
+
# else
|
70
|
+
# Decoding::Result.err("expected String, got #{input_value.class}")
|
71
|
+
# end
|
72
|
+
# end
|
73
|
+
#
|
74
|
+
# You can use the base decoders along with `map` to write more complex decoder. For example, you could
|
75
|
+
# extract a `time_decoder` from the example above:
|
76
|
+
#
|
77
|
+
# time_decoder = D.map(D.string) { Time.at(_1.to_i) }
|
78
|
+
#
|
79
|
+
# When the shape of the incoming data is unknown, you can try out various
|
80
|
+
# decoders in a row to find the first that succeeds using `any`:
|
81
|
+
#
|
82
|
+
# string_or_integer = D.any(D.string, D.integer)
|
83
|
+
# Decoding.decode(string_or_integer, 1) # => Decoding::Ok(1)
|
84
|
+
# Decoding.decode(string_or_integer, '1') # => Decoding::Ok('1')
|
85
|
+
#
|
86
|
+
# You can also base one decoder on a previously decoded value. For example, a
|
87
|
+
# payload might contain a version number describing its format. Use `and_then`
|
88
|
+
# to decode one value and then construct a new decoder to run against the same
|
89
|
+
# input using that value:
|
90
|
+
#
|
91
|
+
# multiple_version_decoder = D.and_then(D.field("version", D.string)) do |version|
|
92
|
+
# if version == "1"
|
93
|
+
# D.field("name", D.string)
|
94
|
+
# else
|
95
|
+
# D.field("fullName", D.string)
|
96
|
+
# end
|
97
|
+
# end
|
98
|
+
#
|
99
|
+
# Now, you have a decoder that can work inputs using format version 1 and 2:
|
100
|
+
#
|
101
|
+
# Decoding.decode(multiple_version_decoder, "version" => "1", "name" => "John")
|
102
|
+
# # => "John"
|
103
|
+
# Decoding.decode(multiple_version_decoder, "version" => "2", "fullName" => "Paul")
|
104
|
+
# # => "Paul"
|
105
|
+
#
|
106
|
+
# The return values of decoding are `Decoding::Result` values, which come in
|
107
|
+
# `Ok` and `Err` subclasses. These describe how the decoding either succeeded or
|
108
|
+
# failed. The `Ok` values contain the decoded result, while the `Err` values
|
109
|
+
# always contain a string error message. It is up to you, as a developer, to
|
110
|
+
# decide how to deal with unsuccessful decoding.
|
111
|
+
module Decoding
|
112
|
+
class Error < StandardError; end
|
113
|
+
|
114
|
+
module_function
|
115
|
+
|
116
|
+
# Run a given `decoder` on the given input `value`.
|
117
|
+
#
|
118
|
+
# @param decoder [Decoding::Decoder<a>]
|
119
|
+
# @param value [Object]
|
120
|
+
# @return [Decoding::Result<a>]
|
121
|
+
def decode(decoder, value) = decoder.call(value)
|
122
|
+
end
|
data/sig/decoding.rbs
ADDED
metadata
ADDED
@@ -0,0 +1,70 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: decoding
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Arjan van der Gaag
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2024-06-07 00:00:00.000000000 Z
|
12
|
+
dependencies: []
|
13
|
+
description:
|
14
|
+
email:
|
15
|
+
- arjan@arjanvandergaag.nl
|
16
|
+
executables: []
|
17
|
+
extensions: []
|
18
|
+
extra_rdoc_files: []
|
19
|
+
files:
|
20
|
+
- ".rspec"
|
21
|
+
- ".rubocop.yml"
|
22
|
+
- ".tool-versions"
|
23
|
+
- ".yardopts"
|
24
|
+
- CHANGELOG.md
|
25
|
+
- CODE_OF_CONDUCT.md
|
26
|
+
- LICENSE.txt
|
27
|
+
- README.md
|
28
|
+
- Rakefile
|
29
|
+
- lib/decoding.rb
|
30
|
+
- lib/decoding/decoder.rb
|
31
|
+
- lib/decoding/decoders.rb
|
32
|
+
- lib/decoding/decoders/and_then.rb
|
33
|
+
- lib/decoding/decoders/any.rb
|
34
|
+
- lib/decoding/decoders/array.rb
|
35
|
+
- lib/decoding/decoders/field.rb
|
36
|
+
- lib/decoding/decoders/hash.rb
|
37
|
+
- lib/decoding/decoders/index.rb
|
38
|
+
- lib/decoding/decoders/map.rb
|
39
|
+
- lib/decoding/decoders/match.rb
|
40
|
+
- lib/decoding/result.rb
|
41
|
+
- lib/decoding/version.rb
|
42
|
+
- sig/decoding.rbs
|
43
|
+
homepage: https://github.com/avdgaag/decoding
|
44
|
+
licenses:
|
45
|
+
- MIT
|
46
|
+
metadata:
|
47
|
+
allowed_push_host: https://rubygems.org
|
48
|
+
homepage_uri: https://github.com/avdgaag/decoding
|
49
|
+
source_code_uri: https://github.com/avdgaag/decoding
|
50
|
+
rubygems_mfa_required: 'true'
|
51
|
+
post_install_message:
|
52
|
+
rdoc_options: []
|
53
|
+
require_paths:
|
54
|
+
- lib
|
55
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
56
|
+
requirements:
|
57
|
+
- - ">="
|
58
|
+
- !ruby/object:Gem::Version
|
59
|
+
version: 3.3.0
|
60
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
61
|
+
requirements:
|
62
|
+
- - ">="
|
63
|
+
- !ruby/object:Gem::Version
|
64
|
+
version: '0'
|
65
|
+
requirements: []
|
66
|
+
rubygems_version: 3.5.3
|
67
|
+
signing_key:
|
68
|
+
specification_version: 4
|
69
|
+
summary: Decode dynamic values into known Ruby data structures
|
70
|
+
test_files: []
|