You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Improve UPGRADING.md instructions for custom types
* Provide an example for taking an existing type and porting it to
the dry-types. This would have saved me some time.
* Removed examples of using `Virtus.model`. It seems confusing to
support dry-types and Virtus at the same time.
Closes#2012
Copy file name to clipboardExpand all lines: UPGRADING.md
+36-17Lines changed: 36 additions & 17 deletions
Original file line number
Diff line number
Diff line change
@@ -9,38 +9,57 @@ After adding dry-types, Ruby 2.4 or newer is required.
9
9
10
10
#### Coercion
11
11
12
-
[Virtus](https://github.com/solnic/virtus) has been replaced by [dry-types](https://dry-rb.org/gems/dry-types/1.2/) for parameter coercion. If your project depends on Virtus, explicitly add it to your `Gemfile`. Also, if Virtus is used for defining custom types
12
+
[Virtus](https://github.com/solnic/virtus) has been replaced by
13
+
[dry-types](https://dry-rb.org/gems/dry-types/1.2/) for parameter
14
+
coercion. If your project depends on Virtus outside of Grape, explicitly
15
+
add it to your `Gemfile`.
16
+
17
+
Here's an example of how to migrate a custom type from Virtus to dry-types:
13
18
14
19
```ruby
15
-
classUser
16
-
includeVirtus.model
20
+
# Legacy Grape parser
21
+
classSecureUriType < Virtus::Attribute
22
+
defcoerce(input)
23
+
URI.parse value
24
+
end
17
25
18
-
attribute :id, Integer
19
-
attribute :name, String
26
+
defvalue_coerced?(input)
27
+
value.is_a? String
28
+
end
20
29
end
21
30
22
-
# somewhere in your API
23
31
params do
24
-
requires :user, type:User
32
+
requires :secure_uri, type:SecureUri
25
33
end
26
34
```
27
35
28
-
Add a class-level `parse` method to the model:
36
+
To use dry-types, we need to:
29
37
30
-
```ruby
31
-
classUser
32
-
includeVirtus.model
38
+
1. Remove the inheritance of `Virtus::Attribute`
39
+
1. Rename `coerce` to `self.parse`
40
+
1. Rename `value_coerced?` to `self.parsed?`
33
41
34
-
attribute :id, Integer
35
-
attribute :name, String
42
+
The custom type must have a class-level `parse` method to the model. A
43
+
class-level `parsed?` is needed if the parsed type differs from the
44
+
defined type. In the example below, since `SecureUri` is not the same
45
+
as `URI::HTTPS`, `self.parsed?` is needed:
36
46
37
-
defself.parse(attrs)
38
-
new(attrs)
47
+
```ruby
48
+
# New dry-types parser
49
+
classSecureUri
50
+
defself.parse(value)
51
+
URI.parse value
52
+
end
53
+
54
+
defself.parsed?(value)
55
+
value.is_a? URI::HTTPS
39
56
end
40
57
end
41
-
```
42
58
43
-
Custom types which don't depend on Virtus don't require any changes.
59
+
params do
60
+
requires :secure_uri, type:SecureUri
61
+
end
62
+
```
44
63
45
64
#### Ensure that Array types have explicit coercions
0 commit comments