From e7beaa5339b96303c90fbae4554a6d6189201306 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Glauco=20Cust=C3=B3dio?= Date: Sat, 4 May 2024 07:37:11 +0100 Subject: [PATCH] document attribute method overriding (#36) --- README.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/README.md b/README.md index 063ccb3..fd778a9 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ $ gem install shale * [Using methods to extract and generate data](#using-methods-to-extract-and-generate-data) * [Delegating fields to child attributes](#delegating-fields-to-child-attributes) * [Additional options](#additional-options) +* [Overriding attribute methods](#overriding-attribute-methods) * [Using custom models](#using-custom-models) * [Supported types](#supported-types) * [Writing your own type](#writing-your-own-type) @@ -1108,6 +1109,40 @@ Person.to_json(person, allow_nan: true) # } ``` +### Overriding attribute methods + +It's possible to override an attribute method to change its output: + +```ruby +class Person < Shale::Mapper + attribute :gender, Shale::Type::String + + def gender + if super == 'm' + 'male' + else + 'female' + end + end +end + +puts Person.from_json('{"gender":"m"}') + +# => +# +# # +``` + +Be conscious that the original attribute value will be lost after its transformation though: + +```ruby +puts User.from_json('{"gender":"m"}').to_json +# => {"gender":"male"} +``` + +It'll no longer return gender `m`. + ### Using custom models By default Shale combines mapper and model into one class. If you want to use your own classes