CLI creation with thor

!ruby-2.7.0p0

This page is a personal memo in a university lecture

thor

What is thor

A tool that allows you to create CLI commands. It seems that git etc. are also developed with this. thor's GitHub is here

How to make CLI commands

First, put what you need

gem install bundler
gem install thor

Generate project

bundle gem <CLI command name> -b

"" is written as hoge below.

Open hoge.gemspec in the created directory with an editor and rewrite the part that is TODO appropriately.

Give permission, install

chmod a+x exe/hoge
bundle install

Write the command processing program in lib/hoge.rb. For example, ↓

require 'thor'
require "hoge/version"

class HogeCLI < Thor
  desc "hoge NAME", "Say hello to NAME"
  def hello(name)
    puts "Hello " + name
  end
end

HogeCLI.start(ARGV)

desc is the explanation that is displayed when you do hoge help. The hoge NAME part represents a command input example, and the Say hello to NAME part represents a description of the command. The class name must end with CLI.

Once the program is complete

bundle update
bundle install

Updated with.

later,

bundle exec exe/hoge

You can execute the created command with.

So that you can use the created command from anywhere

To make the created command available from anywhere

rake install:local

But I was angry without rubocop, so

gem install rubocop

I tried it again after putting it in.

Now from anywhere

hoge hello fuga

You can now call it with.

rubocop

It seems to be something like ruby's code formatter. I wonder if it corresponds to flake8 in python & # x2026 ;?

rubocop hoge.rb

If you do, it will show you where to fix the code.

rubocop --auto-correct hoge.rb

Then, it seems that it will be corrected automatically.


Recommended Posts

CLI creation with thor
Graph creation with JFreeChart
Java multi-project creation with Gradle
API creation with Rails + GraphQL
Added xa-data-source with WildFly 10 CLI
Inquiry application creation with Spring Boot
[Rails] Initial data creation with seed
Web application creation with Nodejs with Docker
6 ways to define options with thor
Beginning with Spring Boot 0. Use Spring CLI
[I get] Until deploying with SAM CLI
"Hello, World!" With Kotlin + CLI in 5 minutes
Tool creation with JavaFX & self-contained package (distribution)
Tool creation with JavaFX & self-contained package (JavaFX edition)