Ruby로 CLI Tool 만들기
출력
htps : // 기주 b. 코 m / 토즈 00 / s ぁ ck_ 후 fy_c ぃ
개발 환경
절차
이번에는 slack_notify_cli라는 gem을 만듭니다.
 1. bundler 설치
설치되지 않은 경우에만.
$ gem install bundler 
 2. 젬의 병아리 만들기
이번에는 테스트도 쓸 예정이므로 -t 옵션을 지정한다.
$ bundle gem slack_notify_cli -t rspec
 3. gemspec 수정
기본적으로 TODO 부분을 편집하면 좋다.
slack_notify_cli.gemspec
Gem::Specification.new do |spec|
  spec.name          = "slack_notify_cli"
  spec.version       = SlackNotifyCli::VERSION
+   spec.authors       = "tozu00"
-   spec.summary       = %q{TODO: Write a short summary, because RubyGems requires one.}↲
-   spec.description   = %q{TODO: Write a longer description or delete this line.}↲
-   spec.homepage      = "TODO: Put your gem's website or public repo URL here."↲
+  spec.summary       = %q{slack notification command line interface. }
+  spec.description   = %q{slack notification command line interface. ex.) get channel list, check auth, send message}
+  spec.homepage      = "https://github.com/tozu00/slack_notify_cli"
 rubygems에 등록하는 경우에는 다음 설정이 있으면 안됩니다.
 외부에 gem을 게시하지 않으려는 경우에만 이 설정이 필요합니다. 그래서 삭제합니다.
slack_notify_cli.gemspec-  # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
-  # to allow pushing to a single host or delete this section to allow pushing to any host.
-  if spec.respond_to?(:metadata)
-    spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
-    spec.metadata["homepage_uri"] = spec.homepage
-    spec.metadata["source_code_uri"] = "TODO: Put your gem's public repo URL here."
-    spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
-  else
-    raise "RubyGems 2.0 or newer is required to protect against " \
-      "public gem pushes."
-  end
 필요한 gem 추가
slack_notify_cli.gemspec
  spec.add_development_dependency "aruba"
  spec.add_dependency "thor"
  spec.add_dependency "slack-ruby-client"
$ gem install bundler 
$ bundle gem slack_notify_cli -t rspec
Gem::Specification.new do |spec|
  spec.name          = "slack_notify_cli"
  spec.version       = SlackNotifyCli::VERSION
+   spec.authors       = "tozu00"
-   spec.summary       = %q{TODO: Write a short summary, because RubyGems requires one.}↲
-   spec.description   = %q{TODO: Write a longer description or delete this line.}↲
-   spec.homepage      = "TODO: Put your gem's website or public repo URL here."↲
+  spec.summary       = %q{slack notification command line interface. }
+  spec.description   = %q{slack notification command line interface. ex.) get channel list, check auth, send message}
+  spec.homepage      = "https://github.com/tozu00/slack_notify_cli"
-  # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
-  # to allow pushing to a single host or delete this section to allow pushing to any host.
-  if spec.respond_to?(:metadata)
-    spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
-    spec.metadata["homepage_uri"] = spec.homepage
-    spec.metadata["source_code_uri"] = "TODO: Put your gem's public repo URL here."
-    spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
-  else
-    raise "RubyGems 2.0 or newer is required to protect against " \
-      "public gem pushes."
-  end
  spec.add_development_dependency "aruba"
  spec.add_dependency "thor"
  spec.add_dependency "slack-ruby-client"
아루바 : 테스트 프레임 워크. CLI 테스트가 쉬워집니다.
thor : CLItool을 작성합니다.
slack-ruby-client : slack의 통지 기능을 실현한다.
4. 명령이 실행되는 클래스 작성
slack-ruby-client의 다음 기능을 구현해보십시오.lib/slack_notify_cli/command.rb
require 'thor'
require 'slack-ruby-client'
Slack.configure do |config|
  config.token = ENV['SLACK_API_TOKEN']
  raise 'Missing ENV[SLACK_API_TOKEN]!' unless config.token
end
module SlackNotifyCli
  class Command < Thor
    desc "slack_notify_cli auth_check", "auth check"
    def auth_check
      client = Slack::Web::Client.new
      puts client.auth_test['ok'] ? "Authentication successed" : "Authentication failed"
    end
    desc "slack_notify_cli channel_list", "get channel list"
    def channel_list
      client = Slack::Web::Client.new
      channels = client.channels_list.channels
      puts channels.map { |c| "##{c.name} #{c.purpose.value}"}
    end
    desc "slack_cli send str:{channel} str:{message}", "send message ex.) slack_cli send \"#general\" \"Hello World\""
    def send(channel, message)
      client = Slack::Web::Client.new
      client.chat_postMessage(channel: channel, text: message, as_user: true)
    end
  end
end
만든 클래스 로드
lib/slack_notify_cli.rb
require "slack_notify_cli/version"
+ require "slack_notify_cli/command"
module SlackNotifyCli
  class Error < StandardError; end
end
5. 실행 파일 만들기
SlackNotifyCli::Command.start에서 CLI를 시작합니다.exe/slack_notify_cli
#!/usr/bin/env ruby
require "slack_notify_cli"
SlackNotifyCli::Command.start
6. bundle install
gem의 설치를 디렉토리의 범위에 한정하고 싶기 때문에,
--path 옵션을 붙여, 인스톨 한다.$ bundle install --path .bundle
7. 명령 실행
환경 변수에 token을 설정하고 명령을 실행합니다.
$ export SLACK_API_TOKEN=xo...
$ bundle exec exe/slack_notify_cli
Commands:
  slack_notify_cli help [COMMAND]                              # Describe available commands or one specific command
  slack_notify_cli slack_cli send str:{channel} str:{message}  # send message ex.) slack_cli send "#general" "Hello World"
  slack_notify_cli slack_notify_cli auth_check                 # auth check
  slack_notify_cli slack_notify_cli channel_list               # get channel list
인수를 지정하지 않으면 도움말을 내주는 것 같습니다.
메시지 보내기
$ bundle exec exe/slack_notify_cli send "#test" "Hello World"
 
굉장히 간단하지 않을까!
 소감
$ bundle exec exe/slack_notify_cli send "#test" "Hello World"
참고 기사
Reference
이 문제에 관하여(Ruby로 CLI Tool 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/tozu00/items/3fc9a14ff0e062ebdb1d텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)