desc 'example', 'an example task' option :file, type: :string, aliases: '-f', desc: 'Delete the file after parsing it' def example puts "executing! argument is #{options[:file]}!" end end
Command.start
さっそく作成したコマンドを実行してみます!
# 初回のみ実行権限を付与 chmod a+x testest
./testest -f sample.file #=> executing! argument is sample.file!
desc 'example', 'an example task' option :file, type: :string, aliases: '-f', desc: 'Delete the file after parsing it' method_option :delete, aliases: '-d', desc: 'Delete the file after parsing it' def example if options[:delete] puts "executing! argument is #{options[:file]} and delete option is true!" else puts "executing! argument is #{options[:file]} and delete option is false!" end end end
Command.start
では先ほど作ったコマンドを実行してみます。
# -d(--delete) オプションを付けない場合 ./testest -f 'sample.file' #=> executing! argument is sample.file and delete option is false!
# -d(--delete) オプションを付ける場合 ./testest -f 'sample.file' -d #=> executing! argument is sample.file and delete option is true!
🚕 Railsの環境情報を取得
Railsの環境情報を使ったコマンドも簡単に作成できます。
class Example < Thor include Thor::Actions desc "init_example", " you can write some description" method_options :force => :boolean, :aliases => "-f" def init_example # Railsの環境情報を読み込み require './config/environment'
if options[:force] if yes?("WARN: Are u sure ?",:yellow) delete_sql = "truncate examples" say "delete all datas from examples ... ", :red ActiveRecord::Base.connection.execute(delete_sql) else say "Cancel!", :red return end end
#TODO end end
👽 Namespaceを付け足す
thorを使いこなす過程でNamespaceが欲しくなるかもです。そんな場合はこちら。
module Sinatra class App < Thor namespace :myapp def install # task code end # other tasks end end