1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 23:28:02 +00:00

Add Handle Named Arguments In A Rake Task as a Rails til

This commit is contained in:
jbranchaud
2021-09-21 10:38:01 -05:00
parent e9ca21dbbb
commit 92ed23fc34
2 changed files with 54 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://crafty-builder-6996.ck.page/e169c61186).
_1152 TILs and counting..._
_1153 TILs and counting..._
---
@@ -702,6 +702,7 @@ _1152 TILs and counting..._
- [Get An Empty ActiveRecord Relation](rails/get-an-empty-activerecord-relation.md)
- [Get The Column Names For A Model](rails/get-the-column-names-for-a-model.md)
- [Get The Current Time](rails/get-the-current-time.md)
- [Handle Named Arguments In A Rake Task](rails/handle-named-arguments-in-a-rake-task.md)
- [Hash Slicing](rails/hash-slicing.md)
- [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md)
- [Include Devise Helpers In Your Controller Tests](rails/include-devise-helpers-in-your-controller-tests.md)

View File

@@ -0,0 +1,52 @@
# Handle Named Arguments In A Rake Task
There are [a number of
ways](https://www.seancdavis.com/blog/4-ways-to-pass-arguments-to-a-rake-task/)
to pass arguments into a Rake task. The standard approach only allows for
positional arguments. When I need named and optional arguments, my preferred
approach is to use environment variables.
Here is a skimmed down version of a user lookup task. Notice the task
definition itself doesn't include any arguments. Instead, a couple optional
values are extracted from the environment (`ENV`) at the beginngin of the task.
```ruby
desc "An example task with named, optional arguments"
task :lookup_user => :environment do
user_id = ENV['USER_ID']
email = ENV['EMAIL']
if user_id.present?
user = User.find(user_id)
if user.blank?
puts "No user for id ##{user_id}"
end
elsif email.present?
user = User.find_by(email: email)
if user.blank?
puts "No user for email #{email}"
end
end
puts "User found" if user.present?
end
```
This task can be invoked in the following ways:
```bash
$ rake lookup_user USER_ID=123
```
```bash
$ rake lookup_user EMAIL="user@example.com"
```
or even with both arguments included, in which case the task has been written
to give precedence to `USER_ID`:
```bash
$ rake lookup_user EMAIL="user@example.com" USER_ID=123
```