blood_contracts-ext 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/.gitignore +12 -0
- data/.rspec +3 -0
- data/.rubocop.yml +31 -0
- data/.travis.yml +19 -0
- data/CHANGELOG.md +23 -0
- data/CODE_OF_CONDUCT.md +74 -0
- data/Gemfile +4 -0
- data/LICENSE +21 -0
- data/README.md +369 -0
- data/Rakefile +6 -0
- data/bin/console +14 -0
- data/bin/setup +8 -0
- data/blood_contracts-ext.gemspec +27 -0
- data/lib/blood_contracts/core/defineable_error.rb +61 -0
- data/lib/blood_contracts/core/exception_caught.rb +33 -0
- data/lib/blood_contracts/core/exception_handling.rb +36 -0
- data/lib/blood_contracts/core/expected_error.rb +16 -0
- data/lib/blood_contracts/core/extractable.rb +85 -0
- data/lib/blood_contracts/core/map_value.rb +45 -0
- data/lib/blood_contracts/core/policy_failure.rb +42 -0
- data/lib/blood_contracts/core/sum_policy_failure.rb +9 -0
- data/lib/blood_contracts/core/tuple_policy_failure.rb +39 -0
- data/lib/blood_contracts/ext/pipe.rb +27 -0
- data/lib/blood_contracts/ext/refined.rb +59 -0
- data/lib/blood_contracts/ext/sum.rb +29 -0
- data/lib/blood_contracts/ext/tuple.rb +28 -0
- data/lib/blood_contracts/ext.rb +28 -0
- data/spec/blood_contracts/ext/exception_caught_spec.rb +50 -0
- data/spec/blood_contracts/ext/expected_error_spec.rb +56 -0
- data/spec/blood_contracts/ext/map_value_spec.rb +54 -0
- data/spec/blood_contracts/ext/policy_failure_spec.rb +151 -0
- data/spec/blood_contracts/ext/policy_spec.rb +138 -0
- data/spec/fixtures/en.yml +19 -0
- data/spec/spec_helper.rb +24 -0
- data/spec/support/fixtures_helper.rb +11 -0
- metadata +202 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: b7753da5bf340600c41348deca62452860ac5663eb238470f5f2af67f72d162e
|
4
|
+
data.tar.gz: a11f44add5d39132210250f8732e23818abaafebdd0558fcfd2eea3084c4f70b
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: d7e28da298037135f8baa122ec04968f2b70137e0379afee26421a744a08b92c1faa8ce224cf2dd2c0fb53a8ebdaf956937c4d17402fa99e704af6901b368328
|
7
|
+
data.tar.gz: a5796575eb357fd0c5753906ebf29e1410372c8ee451165aec8ce070118bcac65b014de53a41f6a005fdcede76a997a45c38b44e39da01358eaca20b21a8d6f1
|
data/.gitignore
ADDED
data/.rspec
ADDED
data/.rubocop.yml
ADDED
@@ -0,0 +1,31 @@
|
|
1
|
+
---
|
2
|
+
|
3
|
+
AllCops:
|
4
|
+
DisplayCopNames: true
|
5
|
+
DisplayStyleGuide: true
|
6
|
+
StyleGuideCopsOnly: true
|
7
|
+
TargetRubyVersion: 2.4
|
8
|
+
Exclude:
|
9
|
+
- examples/*
|
10
|
+
- blood_contracts-ext.gemspec
|
11
|
+
- vendor/bundle/**/*
|
12
|
+
|
13
|
+
Metrics/LineLength:
|
14
|
+
AllowHeredoc: true
|
15
|
+
AllowURI: true
|
16
|
+
URISchemes:
|
17
|
+
- http
|
18
|
+
- https
|
19
|
+
|
20
|
+
Style/ClassAndModuleChildren:
|
21
|
+
Enabled: false
|
22
|
+
|
23
|
+
Style/Documentation:
|
24
|
+
Enabled: false
|
25
|
+
|
26
|
+
Style/StringLiterals:
|
27
|
+
EnforcedStyle: double_quotes
|
28
|
+
|
29
|
+
Naming/FileName:
|
30
|
+
Exclude:
|
31
|
+
- lib/blood_contracts-ext.rb
|
data/.travis.yml
ADDED
@@ -0,0 +1,19 @@
|
|
1
|
+
---
|
2
|
+
sudo: false
|
3
|
+
language: ruby
|
4
|
+
cache: bundler
|
5
|
+
before_install:
|
6
|
+
- gem install bundler --no-document
|
7
|
+
- gem update --system
|
8
|
+
script:
|
9
|
+
- bundle exec rspec
|
10
|
+
- bundle exec rubocop
|
11
|
+
rvm:
|
12
|
+
- 2.4.0
|
13
|
+
- 2.6.0
|
14
|
+
- ruby-head
|
15
|
+
- jruby-head
|
16
|
+
matrix:
|
17
|
+
allow_failures:
|
18
|
+
- rvm: ruby-head
|
19
|
+
- rvm: jruby-head
|
data/CHANGELOG.md
ADDED
@@ -0,0 +1,23 @@
|
|
1
|
+
# Change Log
|
2
|
+
|
3
|
+
All notable changes to this project will be documented in this file.
|
4
|
+
|
5
|
+
The format is based on [Keep a Changelog](http://keepachangelog.com/)
|
6
|
+
and this project adheres to [Semantic Versioning](http://semver.org/).
|
7
|
+
|
8
|
+
## [0.1.0] - [2019-07-04]
|
9
|
+
|
10
|
+
This is a first public release marked in change log with features extracted from production app.
|
11
|
+
Includes:
|
12
|
+
- *BC::Ext::Refined* - exteneded refinement type with support of Extractors and Policy for validation
|
13
|
+
- *Extractable* - is a simple concern that turns your refinement type into a coercer which tries to extract particular fields from the given value,
|
14
|
+
the bonus is that you need no #match method definition, only methods that you passed to `.extract` DSL
|
15
|
+
- *MapValue* - is a type which saves the value in the original form to context and then passes it some mapper class, which should change the
|
16
|
+
form of the input object (e.g. turn it into JSON or XML)
|
17
|
+
- *ExpectedError* - is a validation scenario when something goes wrong during validation but in expected way (e.g. API returns a recoverable error),
|
18
|
+
that type is valid too, but `#unpack` returns a Tram::Policy::Errors
|
19
|
+
- *DefinableError* - is a concern to define single time Tram::Policy::Errors, when you don't want to delegate validation to policy, but you want
|
20
|
+
to store errors in form of Tram::Policy::Errors
|
21
|
+
- *ExceptionCaught and ExceptionHandling* - is a way to turn StandardError inside the type matching into another refinement type, that type is of course
|
22
|
+
ancestor of BC::ContractFailure, but have an additional reader `#exception` which gives you access to the exception and at the same time you could
|
23
|
+
read all the context that was collected till the "exceptional" moment
|
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,74 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
In the interest of fostering an open and welcoming environment, we as
|
6
|
+
contributors and maintainers pledge to making participation in our project and
|
7
|
+
our community a harassment-free experience for everyone, regardless of age, body
|
8
|
+
size, disability, ethnicity, gender identity and expression, level of experience,
|
9
|
+
nationality, personal appearance, race, religion, or sexual identity and
|
10
|
+
orientation.
|
11
|
+
|
12
|
+
## Our Standards
|
13
|
+
|
14
|
+
Examples of behavior that contributes to creating a positive environment
|
15
|
+
include:
|
16
|
+
|
17
|
+
* Using welcoming and inclusive language
|
18
|
+
* Being respectful of differing viewpoints and experiences
|
19
|
+
* Gracefully accepting constructive criticism
|
20
|
+
* Focusing on what is best for the community
|
21
|
+
* Showing empathy towards other community members
|
22
|
+
|
23
|
+
Examples of unacceptable behavior by participants include:
|
24
|
+
|
25
|
+
* The use of sexualized language or imagery and unwelcome sexual attention or
|
26
|
+
advances
|
27
|
+
* Trolling, insulting/derogatory comments, and personal or political attacks
|
28
|
+
* Public or private harassment
|
29
|
+
* Publishing others' private information, such as a physical or electronic
|
30
|
+
address, without explicit permission
|
31
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
32
|
+
professional setting
|
33
|
+
|
34
|
+
## Our Responsibilities
|
35
|
+
|
36
|
+
Project maintainers are responsible for clarifying the standards of acceptable
|
37
|
+
behavior and are expected to take appropriate and fair corrective action in
|
38
|
+
response to any instances of unacceptable behavior.
|
39
|
+
|
40
|
+
Project maintainers have the right and responsibility to remove, edit, or
|
41
|
+
reject comments, commits, code, wiki edits, issues, and other contributions
|
42
|
+
that are not aligned to this Code of Conduct, or to ban temporarily or
|
43
|
+
permanently any contributor for other behaviors that they deem inappropriate,
|
44
|
+
threatening, offensive, or harmful.
|
45
|
+
|
46
|
+
## Scope
|
47
|
+
|
48
|
+
This Code of Conduct applies both within project spaces and in public spaces
|
49
|
+
when an individual is representing the project or its community. Examples of
|
50
|
+
representing a project or community include using an official project e-mail
|
51
|
+
address, posting via an official social media account, or acting as an appointed
|
52
|
+
representative at an online or offline event. Representation of a project may be
|
53
|
+
further defined and clarified by project maintainers.
|
54
|
+
|
55
|
+
## Enforcement
|
56
|
+
|
57
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
58
|
+
reported by contacting the project team at sclinede@gmail.com. All
|
59
|
+
complaints will be reviewed and investigated and will result in a response that
|
60
|
+
is deemed necessary and appropriate to the circumstances. The project team is
|
61
|
+
obligated to maintain confidentiality with regard to the reporter of an incident.
|
62
|
+
Further details of specific enforcement policies may be posted separately.
|
63
|
+
|
64
|
+
Project maintainers who do not follow or enforce the Code of Conduct in good
|
65
|
+
faith may face temporary or permanent repercussions as determined by other
|
66
|
+
members of the project's leadership.
|
67
|
+
|
68
|
+
## Attribution
|
69
|
+
|
70
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
71
|
+
available at [http://contributor-covenant.org/version/1/4][version]
|
72
|
+
|
73
|
+
[homepage]: http://contributor-covenant.org
|
74
|
+
[version]: http://contributor-covenant.org/version/1/4/
|
data/Gemfile
ADDED
data/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2019 Sergey Dolganov
|
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,369 @@
|
|
1
|
+
[![Build Status](https://travis-ci.org/sclinede/blood_contracts-ext.svg?branch=master)][travis]
|
2
|
+
[![Code Climate](https://codeclimate.com/github/sclinede/blood_contracts-ext/badges/gpa.svg)][codeclimate]
|
3
|
+
|
4
|
+
[gem]: https://rubygems.org/gems/blood_contracts-ext
|
5
|
+
[travis]: https://travis-ci.org/sclinede/blood_contracts-ext
|
6
|
+
[codeclimate]: https://codeclimate.com/github/sclinede/blood_contracts-ext
|
7
|
+
|
8
|
+
# BloodContracts::Ext
|
9
|
+
|
10
|
+
Refinement types are implemented in BloodContracts::Core, but in production we found several patterns to use with types.
|
11
|
+
Let me share them with you.
|
12
|
+
|
13
|
+
Welcome, **extended refinement types**.
|
14
|
+
|
15
|
+
All those extensions are listed below, stay tuned.
|
16
|
+
|
17
|
+
## Installation
|
18
|
+
|
19
|
+
Add this line to your application's Gemfile:
|
20
|
+
|
21
|
+
```ruby
|
22
|
+
gem 'blood_contracts-ext'
|
23
|
+
```
|
24
|
+
|
25
|
+
And then execute:
|
26
|
+
|
27
|
+
$ bundle
|
28
|
+
|
29
|
+
Or install it yourself as:
|
30
|
+
|
31
|
+
$ gem install blood_contracts-ext
|
32
|
+
|
33
|
+
## Usage
|
34
|
+
|
35
|
+
This gems consists mostly of Concerns and Refined classes that extends the powers of refinement types.
|
36
|
+
|
37
|
+
### BC::ExceptionHandling
|
38
|
+
|
39
|
+
First of all sometimes it is great to replace the usual exception handling with refinement types, because
|
40
|
+
inside type you have much more context then just the exception and its backtrace.
|
41
|
+
|
42
|
+
For that scenario you only need to prepend your BC::Refined class with BC::ExceptionHandling and when
|
43
|
+
the StandardError happen inside your matching pipeline it will turn into BC::ExceptionCaught type
|
44
|
+
(which is of course just another ancestor of BC::ContractFailure).
|
45
|
+
|
46
|
+
```ruby
|
47
|
+
class JsonType < BC::Refined
|
48
|
+
prepend BC::ExceptionHandling
|
49
|
+
|
50
|
+
def match
|
51
|
+
@context[:json_type_input] = value
|
52
|
+
@context[:parsed_json] = JSON.parse(@context[:json_type_input])
|
53
|
+
self
|
54
|
+
end
|
55
|
+
end
|
56
|
+
|
57
|
+
match = JsonType.match(Class.new) # => #<BC::ExceptionCaught ...>
|
58
|
+
match.exception # => TypeError
|
59
|
+
match.context # => { :json_type_input => #<Class>, :exception => TypeError }
|
60
|
+
```
|
61
|
+
|
62
|
+
Now you have access to both the exception (the `#exception` reader) and matching context (the `#context` reader).
|
63
|
+
|
64
|
+
### BC::DefinableError
|
65
|
+
|
66
|
+
Imagine you have an error message you want to return for your validation, but you have to worry about the translations.
|
67
|
+
With BC::DefineableError you don't have to. You just extend your class with `BC::DefinableError.new(:translations_root)` and
|
68
|
+
you have simple DSL to define translatable and composable errors.
|
69
|
+
|
70
|
+
```ruby
|
71
|
+
class EmailType < ::BC::Refined
|
72
|
+
extend BC::DefineableError.new(:type_validations)
|
73
|
+
REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
|
74
|
+
INVALID_EMAIL = define_error(:invalid_email)
|
75
|
+
|
76
|
+
def match
|
77
|
+
context[:email_input] = value.to_s
|
78
|
+
return failure(INVALID_EMAIL) if context[:email_input] !~ REGEX
|
79
|
+
context[:email] = context[:email_input]
|
80
|
+
|
81
|
+
self
|
82
|
+
end
|
83
|
+
end
|
84
|
+
|
85
|
+
match = Email.match("not-an-email") # => #<BC::ContractFailure ...>
|
86
|
+
|
87
|
+
# en.yml should include translation for en.type_validations.email_type.invalid_email
|
88
|
+
# e.g. "Given value is not a valid email address"
|
89
|
+
match.errors.reduce(:merge).messages # => ["Given value is not a valid email address"]
|
90
|
+
```
|
91
|
+
|
92
|
+
Of course you may prefer a shortcut here, when you use ::BC::Ext::Refined as a base class your failures are
|
93
|
+
wrapped into BC::PolicyFailure with even better Tram::Policy integration.
|
94
|
+
|
95
|
+
```ruby
|
96
|
+
class EmailType < ::BC::Ext::Refined
|
97
|
+
extend BC::DefineableError.new(:type_validations)
|
98
|
+
REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
|
99
|
+
INVALID_EMAIL = define_error(:invalid_email)
|
100
|
+
|
101
|
+
def match
|
102
|
+
context[:email_input] = value.to_s
|
103
|
+
return failure(INVALID_EMAIL) if context[:email_input] !~ REGEX
|
104
|
+
context[:email] = context[:email_input]
|
105
|
+
|
106
|
+
self
|
107
|
+
end
|
108
|
+
end
|
109
|
+
|
110
|
+
match = Email.match("not-an-email") # => #<BC::PolicyFailure ...>
|
111
|
+
|
112
|
+
# en.yml should include translation for en.type_validations.email_type.invalid_email
|
113
|
+
# e.g. "Given value is not a valid email address"
|
114
|
+
match.messages # => ["Given value is not a valid email address"]
|
115
|
+
```
|
116
|
+
|
117
|
+
As simple as that! Do you still remember our "patter matching" usage?
|
118
|
+
It's working anyways:
|
119
|
+
|
120
|
+
```ruby
|
121
|
+
case match = Email.match("not-an-email")
|
122
|
+
when Email
|
123
|
+
# Validation succeeded
|
124
|
+
# Use #unpack or #context to extract the data
|
125
|
+
match # => #<Email ...>
|
126
|
+
when BC::PolicyFailure
|
127
|
+
# You have access here to #message and #policy_errors methods
|
128
|
+
match # => #<BC::PolicyFailure ...>
|
129
|
+
when BC::ContractFailure
|
130
|
+
# No fancy Tram::Policy integration but anyway #unpack or #messages at your serivce
|
131
|
+
match # => #<BC::ContractFailure>
|
132
|
+
else raise # Remember to be exhaustive
|
133
|
+
end
|
134
|
+
```
|
135
|
+
|
136
|
+
### BC::MapValue
|
137
|
+
|
138
|
+
Another usual scenario is to transform the value of your type but when logic is too complex
|
139
|
+
you prefer to use another class for that. For that case you may try BC::MapValue type which
|
140
|
+
will be regular part of your pipeline.
|
141
|
+
|
142
|
+
Let's imagine you want to change transform your ActiveModel object to some json through the class.
|
143
|
+
Not a big deal, look at the example:
|
144
|
+
|
145
|
+
```ruby
|
146
|
+
module UPS
|
147
|
+
class JsonRequests::Rates
|
148
|
+
def self.call(origin_country:, destination_country:, weight:)
|
149
|
+
JSON.pretty_generate(
|
150
|
+
"RateRequest": {
|
151
|
+
"Shipment": {
|
152
|
+
"ShipFrom": origin_country,
|
153
|
+
"ShipTo": destination_country,
|
154
|
+
"Service": { "Code": "65" },
|
155
|
+
"Package": {
|
156
|
+
"PackagingType": { "Code": "00" },
|
157
|
+
"PackageWeight": {
|
158
|
+
"UnitOfMeasurement": { "Code": "KGS" },
|
159
|
+
"Weight": weight.to_s,
|
160
|
+
}
|
161
|
+
}
|
162
|
+
}
|
163
|
+
}
|
164
|
+
)
|
165
|
+
end
|
166
|
+
end
|
167
|
+
|
168
|
+
class ParcelType < BC::Refined
|
169
|
+
prepend BC::ExceptionHandling
|
170
|
+
|
171
|
+
def match
|
172
|
+
parcel = value
|
173
|
+
context.merge!(
|
174
|
+
origin_country: parcel.origin_address.country,
|
175
|
+
destination_country: parcel.destination_address.country,
|
176
|
+
weight: parcel.weight
|
177
|
+
)
|
178
|
+
end
|
179
|
+
|
180
|
+
def mapped
|
181
|
+
@context.slice(:origin_country, :destination_country, :weight)
|
182
|
+
end
|
183
|
+
end
|
184
|
+
|
185
|
+
RatesRequestType = ParcelType.and_then(BC::MapValue.with(JsonRequests::Rates))
|
186
|
+
end
|
187
|
+
|
188
|
+
match = UPS::RatesRequestType.match(Parcel.find(123)) # => #<BC::MapValue ...>
|
189
|
+
match.unpack # =>
|
190
|
+
# => {
|
191
|
+
# "RateRequest": {
|
192
|
+
# "Shipment": {
|
193
|
+
# "ShipFrom": "LV",
|
194
|
+
# "ShipTo": "US",
|
195
|
+
# "Service": { "Code": "65" },
|
196
|
+
# "Package": {
|
197
|
+
# "PackagingType": { "Code": "00" },
|
198
|
+
# "PackageWeight": {
|
199
|
+
# "UnitOfMeasurement": { "Code": "KGS" },
|
200
|
+
# "Weight": "1.15"
|
201
|
+
# }
|
202
|
+
# }
|
203
|
+
# }
|
204
|
+
# }
|
205
|
+
# }
|
206
|
+
|
207
|
+
UPS::RatesRequestType.match("not-a-parcel") # => #<BC::ExceptionCaught ...>
|
208
|
+
```
|
209
|
+
|
210
|
+
### BC::Extractable
|
211
|
+
|
212
|
+
You may notice that in huge number of cases your type is a coercer from an arbitrary object.
|
213
|
+
So you may look at the Refinement type as "extractor".
|
214
|
+
That only means you have to use several methods to parse the context from the value.
|
215
|
+
|
216
|
+
That best example is attempt to use single type for different types of input
|
217
|
+
|
218
|
+
```ruby
|
219
|
+
class AddressType < BC::Refined
|
220
|
+
extend BC::Extractable
|
221
|
+
prepend BC::ExceptionHandling
|
222
|
+
|
223
|
+
extract :city
|
224
|
+
extract :country_code, method_name: :country
|
225
|
+
extract :street
|
226
|
+
|
227
|
+
def city
|
228
|
+
return value.city if value.respond_to?(:city)
|
229
|
+
value.to_h
|
230
|
+
.transform_keys(&:to_s)
|
231
|
+
.values_at("city", "City")
|
232
|
+
.compact
|
233
|
+
.first
|
234
|
+
end
|
235
|
+
|
236
|
+
def country
|
237
|
+
return value.country if value.respond_to?(:country)
|
238
|
+
value.to_h
|
239
|
+
.transform_keys(&:to_s)
|
240
|
+
.values_at("country", "country_code", "CountryCode")
|
241
|
+
.compact
|
242
|
+
.first
|
243
|
+
end
|
244
|
+
|
245
|
+
def street
|
246
|
+
return value.street if value.respond_to?(:street)
|
247
|
+
value.to_h
|
248
|
+
.transform_keys(&:to_s)
|
249
|
+
.values_at("street", "street_line", "StreetLine")
|
250
|
+
.compact
|
251
|
+
.first
|
252
|
+
end
|
253
|
+
end
|
254
|
+
|
255
|
+
Address = Struct.new(:country, :city, :street)
|
256
|
+
```
|
257
|
+
|
258
|
+
That's just a definition, but let's take a look how it will behave in runtime:
|
259
|
+
|
260
|
+
```ruby
|
261
|
+
address_model = Address.new("RU", "Moscow", "Novoslobodskaya street")
|
262
|
+
AddressType.match(address_model) # => #<AddressType ...>
|
263
|
+
|
264
|
+
json_address = '{"CountryCode": "RU", "City": "Moscow", "StreetLine": "ul. Novoslobodskaya"}'
|
265
|
+
AddressType.match(JSON.parse(json_address)) # => #<AddressType ...>
|
266
|
+
|
267
|
+
AddressType.match("anything_else") # => #<BC::ExceptionCaught ...>
|
268
|
+
```
|
269
|
+
|
270
|
+
### BC::PolicyFailure
|
271
|
+
|
272
|
+
There is a great abstraction for validation called Policy object. I like the Tram::Policy implementation, so
|
273
|
+
now you're able to delegate validation logic to an external Policy object.
|
274
|
+
|
275
|
+
But, sometimes you may prefer to use only Tram::Policy::Errors abstraction for the matching errors.
|
276
|
+
For that case, you just need to use `self.failure_klass = BC::PolicyFailure` in your type.
|
277
|
+
|
278
|
+
```ruby
|
279
|
+
class Phone < ::BC::Refined
|
280
|
+
self.failure_klass = BC::PolicyFailure
|
281
|
+
REGEX = /\A(\+7|8)(9|8)\d{9}\z/i
|
282
|
+
|
283
|
+
def match
|
284
|
+
context[:phone_input] = value.to_s
|
285
|
+
clean_phone = context[:phone_input].gsub(/[\s\(\)-]/, "")
|
286
|
+
|
287
|
+
# translation key is: en.tram-policy.phone.invalid_phone
|
288
|
+
return failure(:invalid_phone) if clean_phone !~ REGEX
|
289
|
+
context[:clean_phone] = clean_phone
|
290
|
+
|
291
|
+
self
|
292
|
+
end
|
293
|
+
end
|
294
|
+
```
|
295
|
+
|
296
|
+
Not a big difference? But, now all your failure calls generate Tram::Policy::Error, which easily translates
|
297
|
+
using I18n.
|
298
|
+
|
299
|
+
### BC::Ext::Refined
|
300
|
+
|
301
|
+
You just saw several fancy tools around the BC::Refined. So, why don't we have everything inside that class?
|
302
|
+
Because we try to keep things simple and transparent. But.
|
303
|
+
|
304
|
+
If you prefer to have all that tooling in your types - "easy-peasy", use brand new BC::Ext::Refined.
|
305
|
+
|
306
|
+
BC::Ext::Refined - is just extended version of BC::Refined (extended by concerns mentioned above).
|
307
|
+
|
308
|
+
### BC::ExpectedError
|
309
|
+
|
310
|
+
Finally, when you validate responses from API, sometimes "error" is just one of expected scenarios.
|
311
|
+
That is why you may prefer special base class for those matching cases.
|
312
|
+
|
313
|
+
Welcome - BC::ExpectedError, it's just ancestor of BC::Ext::Refined and by default it maps the context to Tram::Policy::Errors.
|
314
|
+
|
315
|
+
```ruby
|
316
|
+
module RubygemsAPI
|
317
|
+
class PlainTextError < BC::ExpectedError
|
318
|
+
def match
|
319
|
+
@context[:parsed] ||= JSON.parse(value)
|
320
|
+
rescue JSON::ParserError
|
321
|
+
@context[:plain_text] = value.to_s
|
322
|
+
self
|
323
|
+
end
|
324
|
+
end
|
325
|
+
|
326
|
+
class JsonType < BC::Ext::Refined
|
327
|
+
def match
|
328
|
+
@context[:parsed] ||= JSON.parse(value)
|
329
|
+
self
|
330
|
+
end
|
331
|
+
|
332
|
+
def mapped
|
333
|
+
@context[:parsed]
|
334
|
+
end
|
335
|
+
end
|
336
|
+
|
337
|
+
Response = JsonType.or_a(PlainTextError)
|
338
|
+
end
|
339
|
+
|
340
|
+
RubygemsAPI::Response.match('{"project": ...}') # => #<JsonType ...>
|
341
|
+
|
342
|
+
match = RubygemsAPI::Response.match('Project not found!') # => #<PlainTextError ...>
|
343
|
+
|
344
|
+
# translation key: en.contracts.rubygems_api/plain_text_error.message
|
345
|
+
match.unpack # => "Service responded with a message: `Project not found!`"
|
346
|
+
```
|
347
|
+
|
348
|
+
### Summary
|
349
|
+
|
350
|
+
That covers all the relevant scenarios for types and contract validations.
|
351
|
+
If you have a case that is not covered and you find it useful - feel free to [open an Issue](https://github.com/sclinede/blood_contracts-ext/issues/new)
|
352
|
+
|
353
|
+
## Development
|
354
|
+
|
355
|
+
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.
|
356
|
+
|
357
|
+
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 tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
358
|
+
|
359
|
+
## Contributing
|
360
|
+
|
361
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/sclinede/blood_contracts-ext. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
|
362
|
+
|
363
|
+
## License
|
364
|
+
|
365
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
366
|
+
|
367
|
+
## Code of Conduct
|
368
|
+
|
369
|
+
Everyone interacting in the BloodContracts::Ext project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/sclinede/blood_contracts-ext/blob/master/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
data/bin/console
ADDED
@@ -0,0 +1,14 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
|
3
|
+
require "bundler/setup"
|
4
|
+
require "blood_contracts/ext"
|
5
|
+
|
6
|
+
# You can add fixtures and/or initialization code here to make experimenting
|
7
|
+
# with your gem easier. You can also use a different console, if you like.
|
8
|
+
|
9
|
+
# (If you use this, don't forget to add pry to your Gemfile!)
|
10
|
+
# require "pry"
|
11
|
+
# Pry.start
|
12
|
+
|
13
|
+
require "irb"
|
14
|
+
IRB.start(__FILE__)
|
data/bin/setup
ADDED
@@ -0,0 +1,27 @@
|
|
1
|
+
Gem::Specification.new do |gem|
|
2
|
+
gem.name = "blood_contracts-ext"
|
3
|
+
gem.version = "0.1.0"
|
4
|
+
gem.authors = ["Sergey Dolganov (sclinede)"]
|
5
|
+
gem.email = ["sclinede@evilmartians.com"]
|
6
|
+
|
7
|
+
gem.summary = "Extra helpers for BloodContracts::Core"
|
8
|
+
gem.description = "Extra helpers for BloodContracts::Core"
|
9
|
+
gem.homepage = "https://github.com/sclinede/blood_contracts-ext"
|
10
|
+
gem.license = "MIT"
|
11
|
+
|
12
|
+
gem.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
|
13
|
+
gem.test_files = gem.files.grep(/^spec/)
|
14
|
+
gem.extra_rdoc_files = Dir["CODE_OF_CONDUCT.md", "README.md", "LICENSE", "CHANGELOG.md"]
|
15
|
+
|
16
|
+
gem.required_ruby_version = ">= 2.4"
|
17
|
+
|
18
|
+
gem.add_runtime_dependency "blood_contracts-core", "~> 0.4"
|
19
|
+
gem.add_runtime_dependency "tram-policy" , "~> 2.0"
|
20
|
+
gem.add_runtime_dependency "i18n", "~> 1.0"
|
21
|
+
|
22
|
+
gem.add_development_dependency "bundler", "~> 2.0"
|
23
|
+
gem.add_development_dependency "pry"
|
24
|
+
gem.add_development_dependency "rake", "~> 10.0"
|
25
|
+
gem.add_development_dependency "rspec", "~> 3.0"
|
26
|
+
gem.add_development_dependency "rubocop", "~> 0.49"
|
27
|
+
end
|