Run Rake Tasks on the Rails Console

I usually run my rake tasks in production in this sequence

```
      require 'rake'
      Rails.application.load_tasks
      Rake::Task[task_name]
```

Often repeating the same three commands over and over again. Tedious.

Then I researched how I can make this better.

And I just found that IRB now has a new way of extending the Rails console, here , instead of the old `Rails::ConsoleMethods`, which will be deprecated in Rails 8

Here's how I added command that is now executable from my Rails console:

1. Create a new file in `lib/irb_commands/run_rake_task.rb`

2. Have the following code in it

```
require "irb/command"

# Run "help run_rake_task" to see the help message

module IrbCommands
  class RunRakeTask < IRB::Command::Base
    category "Rails"
    description "Run a Rake task"
    help_message <<~HELP
      Run a Rake task from within the Rails console.

      Usage: run_rake_task <task_name> [arg1 arg2 ...]

      Examples:
        run_rake_task db:migrate
        run_rake_task "my:task[arg1,arg2]"
    HELP

    def execute(*args)
      task_name = args.shift
      raise ArgumentError, "Task name is required" if task_name.nil?

      require "rake"
      Rails.application.load_tasks
      task = Rake::Task[task_name]

      if args.empty?
        task.invoke
      else
        task.invoke(*args)
      end
    rescue => e
      Rails.logger.error("Error running rake task '#{task_name}': #{e.message}")
      Rails.logger.error(e.backtrace.join("\n"))
    ensure
      task&.reenable
    end
  end
end

IRB::Command.register(:run_rake_task, IrbCommands::RunRakeTask)
```

3. Create an initializer to load the above code in you Rails environment. Mine is in `config/initializers/irb.rb`

```
Dir[Rails.root.join("lib/irb_commands/*.rb")].each { |file| require file }
```

4. Fire up `rails console` to test

5. Run `help run_rake_task` and profit!

Screenshot 2024-09-17 at 09.37.38.png 44.9 KB