1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Mask An ActiveRecord Attribute as a Rails til

This commit is contained in:
jbranchaud
2021-04-01 12:05:41 -05:00
parent 00d959110a
commit f2c179f60e
2 changed files with 41 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
_1104 TILs and counting..._ _1105 TILs and counting..._
--- ---
@@ -694,6 +694,7 @@ _1104 TILs and counting..._
- [Make ActionMailer Synchronous In Test](rails/make-action-mailer-synchronous-in-test.md) - [Make ActionMailer Synchronous In Test](rails/make-action-mailer-synchronous-in-test.md)
- [Manually Run A Migration From Rails Console](rails/manually-run-a-migration-from-rails-console.md) - [Manually Run A Migration From Rails Console](rails/manually-run-a-migration-from-rails-console.md)
- [Mark For Destruction](rails/mark-for-destruction.md) - [Mark For Destruction](rails/mark-for-destruction.md)
- [Mask An ActiveRecord Attribute](rails/mask-an-activerecord-attribute.md)
- [Merge A Scope Into An ActiveRecord Query](rails/merge-a-scope-into-an-activerecord-query.md) - [Merge A Scope Into An ActiveRecord Query](rails/merge-a-scope-into-an-activerecord-query.md)
- [Migrating Up Down Up](rails/migrating-up-down-up.md) - [Migrating Up Down Up](rails/migrating-up-down-up.md)
- [Order Matters For `rescue_from` Blocks](rails/order-matters-for-rescue-from-blocks.md) - [Order Matters For `rescue_from` Blocks](rails/order-matters-for-rescue-from-blocks.md)

View File

@@ -0,0 +1,39 @@
# Mask An ActiveRecord Attribute
Let's say we have a `User` model with backing table that has an `email`
attribute.
If we look up a `User` record, we can grab its email because Rails provides an
accessor to that attribute under the hood.
```ruby
> user.email
'Liz.Lemon@example.com'
```
We can write a custom `#email` method on `User` to mask that attribute. We
could do this for any number of reasons. One might be to always downcase the
email before retrieving it and using it througout app code.
```ruby
class User < ApplicationRecord
def email
read_attribute(:email).downcase
end
end
```
This uses the
[`#read_attribute`](https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Read.html#method-i-read_attribute)
method which retreives the type casted value before hitting the accessor
method. We have to do this, rather than calling `#email` directly, because that
would result in an infinite loop.
```ruby
> user.email
'liz.lemon@example.com'
```
I'd probably handle this email scenario at the DB-layer. Nevertheless, this
demonstrates a technique we can use in a variety of scenarios at the
Rails-layer.