File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -65,6 +65,7 @@ $ gem install shale
65
65
* [ Using methods to extract and generate data] ( #using-methods-to-extract-and-generate-data )
66
66
* [ Delegating fields to child attributes] ( #delegating-fields-to-child-attributes )
67
67
* [ Additional options] ( #additional-options )
68
+ * [ Overriding attribute methods] ( #overriding-attribute-methods )
68
69
* [ Using custom models] ( #using-custom-models )
69
70
* [ Supported types] ( #supported-types )
70
71
* [ Writing your own type] ( #writing-your-own-type )
@@ -1108,6 +1109,40 @@ Person.to_json(person, allow_nan: true)
1108
1109
# }
1109
1110
```
1110
1111
1112
+ ### Overriding attribute methods
1113
+
1114
+ It's possible to override an attribute method to change its output:
1115
+
1116
+ ``` ruby
1117
+ class Person < Shale ::Mapper
1118
+ attribute :gender , Shale ::Type ::String
1119
+
1120
+ def gender
1121
+ if super == ' m'
1122
+ ' male'
1123
+ else
1124
+ ' female'
1125
+ end
1126
+ end
1127
+ end
1128
+
1129
+ puts Person .from_json(' {"gender":"m"}' )
1130
+
1131
+ # =>
1132
+ #
1133
+ # #<Person:0x00007f9bc3086d60
1134
+ # @gender="male">
1135
+ ```
1136
+
1137
+ Be conscious that the original attribute value will be lost after its transformation though:
1138
+
1139
+ ``` ruby
1140
+ puts User .from_json(' {"gender":"m"}' ).to_json
1141
+ # => {"gender":"male"}
1142
+ ```
1143
+
1144
+ It'll no longer return gender ` m ` .
1145
+
1111
1146
### Using custom models
1112
1147
1113
1148
By default Shale combines mapper and model into one class. If you want to use your own classes
You can’t perform that action at this time.
0 commit comments