Custom CLI commands in Ruby on Rails

August 5, 2022  ‐ 1 min read

Web frameworks like Django or Laravel allow you to create custom CLI commands for your application. Which allow you to do some run some tasks, or mutations on your models for example.

Ruby on Rails doesn't support the creation of commands in a similar manner. That would be, that is, creating commands isn't built into Rails in a standardized way.

How you would accomplish the same, and (sort of) create a custom CLI command with Ruby on Rails is by making use of the rails runner command. Which allows you to run a file by file path or run a line of code directly.

The option to run a file by path is the option we're interested in here. This allows you to run a piece of code like:

$ rails runner "lib/commands/update_users.rb"