Last week, while creating a small Rails app for myself, I had to import data from an XML file. I wanted to add a command line task for it. I could’ve used rake for this, but I needed to input the path to the file through a command line parameter, and rake isn’t ideal for that. Fortunately, there’s another tool that’s better suited for this task: Thor.
Thor, created by the Rails team, is a tool designed to assist in building command line utilities. Rails itself uses Thor for its command line commands.
If you want to add a custom task to your Rails app with Thor, you can create a file in lib/tasks
with the .thor
extension.
Let’s see an example:
# lib/tasks/import.thor
require_relative "../../config/environment"
class Import < Thor
desc "import_from_the_dump_file PATH_TO_FILE", "Import records from dump"
def import_from_the_dump_file(path_to_file)
# parse the file and import the records
end
end
In this file, we start by requiring the Rails app to access models and whatever else we need. Next, we subclass Thor, and each method we define in this class becomes a task.
For documentation, we use the desc
method. It accepts the method name and potential parameters as the first parameter, and the description as the second one.
When we call thor -T
, we will see that description:
$ thor -T
import
------
thor import:import_from_the_dump_file PATH_TO_FILE # Import records from dump
If a method expects a parameter, we can just simply pass that in from the command line:
$ thor import:import_from_the_dump_file ~/Downloads/export.dump
These are the absolute basics of Thor. But it is a very powerful tool with support for asking user input, adding options to tasks, etc.
I will write a long form article to cover those too.
Did you enjoy reading this? Sign up to the Rails Tricks newsletter for more content like this!
Or follow me on Twitter
I run an indie startup providing vulnerability scanning for your Ruby on Rails app.
It is free to use at the moment, and I am grateful for any feedback about it.If you would like to give it a spin, you can do it here: Vulnerability Scanning for your Ruby on Rails app!