Skip to content

Commit 7212785

Browse files
committed
Add Ensure A Rake Task Cannot Write Data as a Rails TIL
1 parent ead1ba4 commit 7212785

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1281 TILs and counting..._
13+
_1282 TILs and counting..._
1414

1515
---
1616

@@ -789,6 +789,7 @@ _1281 TILs and counting..._
789789
- [Demodulize A Class Name](rails/demodulize-a-class-name.md)
790790
- [Different Ways To Add A Foreign Key Reference](rails/different-ways-to-add-a-foreign-key-reference.md)
791791
- [Disambiguate Where In A Joined Relation](rails/disambiguate-where-in-a-joined-relation.md)
792+
- [Ensure A Rake Task Cannot Write Data](rails/ensure-a-rake-task-cannot-write-data.md)
792793
- [Ensure Migrations Use The Latest Schema](rails/ensure-migrations-use-the-latest-schema.md)
793794
- [Find Or Create A Record With FactoryBot](rails/find-or-create-a-record-with-factory-bot.md)
794795
- [Find Records With Multiple Associated Records](rails/find-records-with-multiple-associated-records.md)
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Ensure A Rake Task Cannot Write Data
2+
3+
Let's say we are writing a substantially complex rake task for aggregating,
4+
arranging, and exporting data from our app's database. The idea is to run this
5+
rake task against production.
6+
7+
There is no part of this rake task that needs to write data. It should act as a
8+
read-only script. And in fact, we can ensure it isn't able to write any data.
9+
We can do that by putting `ApplicationRecord` in read-only mode.
10+
11+
```ruby
12+
task big_export_rake_task: :environment do
13+
class ApplicationRecord
14+
def readonly?
15+
true
16+
end
17+
end
18+
19+
# a bunch of logic ...
20+
puts 'this gets executed'
21+
22+
# Call method that inadvertently writes data
23+
User.update(email: 'readonly@email.com')
24+
25+
# more logic ...
26+
puts 'this does not get executed'
27+
end
28+
```
29+
30+
Because we have made all of `ApplicationRecord` read-only, when we run this
31+
task, it is immediately going to rollback the changes that were attempted and
32+
then raise an error which aborts the rest of the rake task.
33+
34+
We'll see some messaging like this:
35+
36+
```
37+
rake aborted!
38+
ActiveRecord::ReadOnlyRecord: User is marked as readonly
39+
```
40+
41+
h/t [Dillon Hafer](https://dillonhafer.com/)

0 commit comments

Comments
 (0)