Skip to content

Commit

Permalink
document attribute method overriding (kgiszczak#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
glaucocustodio committed May 4, 2024
1 parent a51edda commit e7beaa5
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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"}')

# =>
#
# #<Person:0x00007f9bc3086d60
# @gender="male">
```

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
Expand Down

0 comments on commit e7beaa5

Please sign in to comment.