mirror of
https://github.com/jbranchaud/til
synced 2026-01-05 08:08:02 +00:00
Add Run A Rake Task Programmatically as a Rails TIL
This commit is contained in:
@@ -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).
|
||||
|
||||
_1207 TILs and counting..._
|
||||
_1208 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -782,6 +782,7 @@ _1207 TILs and counting..._
|
||||
- [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md)
|
||||
- [Rollback A Specific Migration Out Of Order](rails/rollback-a-specific-migration-out-of-order.md)
|
||||
- [Rounding Numbers With Precision](rails/rounding-numbers-with-precision.md)
|
||||
- [Run A Rake Task Programmatically](rails/run-a-rake-task-programmatically.md)
|
||||
- [Run Some Code Whenever Rails Console Starts](rails/run-some-code-whenever-rails-console-starts.md)
|
||||
- [Schedule Sidekiq Jobs Out Into The Future](rails/schedule-sidekiq-jobs-out-into-the-future.md)
|
||||
- [Secure Passwords With Rails And Bcrypt](rails/secure-passwords-with-rails-and-bcrypt.md)
|
||||
|
||||
35
rails/run-a-rake-task-programmatically.md
Normal file
35
rails/run-a-rake-task-programmatically.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# Run A Rake Task Programmatically
|
||||
|
||||
Typically the way to run a rake task is with the `rake` command from the
|
||||
command line.
|
||||
|
||||
```bash
|
||||
$ rake example:env
|
||||
```
|
||||
|
||||
What if you have a rake task that you want to invoke as part of a Ruby script
|
||||
or from somewhere in your Rails codebase?
|
||||
|
||||
Your tasks can be called programmatically as well.
|
||||
|
||||
Consider these two rake tasks:
|
||||
|
||||
```ruby
|
||||
namespace :example do
|
||||
task :env do
|
||||
puts "Current Environment: #{Rails.env.upcase}"
|
||||
end
|
||||
|
||||
task :message, [:msg] do |task, args|
|
||||
puts "Message: #{args[:msg]}"
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
These can be called from somewhere else by referencing and invoking them like
|
||||
so.
|
||||
|
||||
```ruby
|
||||
Rake::Task["example:env"].invoke
|
||||
Rake::Task["example:message"].invoke("Nice rake task!")
|
||||
```
|
||||
Reference in New Issue
Block a user