Skip to content

Commit e7beaa5

Browse files
document attribute method overriding (#36)
1 parent a51edda commit e7beaa5

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ $ gem install shale
6565
* [Using methods to extract and generate data](#using-methods-to-extract-and-generate-data)
6666
* [Delegating fields to child attributes](#delegating-fields-to-child-attributes)
6767
* [Additional options](#additional-options)
68+
* [Overriding attribute methods](#overriding-attribute-methods)
6869
* [Using custom models](#using-custom-models)
6970
* [Supported types](#supported-types)
7071
* [Writing your own type](#writing-your-own-type)
@@ -1108,6 +1109,40 @@ Person.to_json(person, allow_nan: true)
11081109
# }
11091110
```
11101111

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+
11111146
### Using custom models
11121147

11131148
By default Shale combines mapper and model into one class. If you want to use your own classes

0 commit comments

Comments
 (0)