Class: Slkecho::OptionParser

Inherits:
Object
  • Object
show all
Defined in:
lib/slkecho/option_parser.rb

Instance Method Summary collapse

Instance Method Details

#build_options(argv) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/slkecho/option_parser.rb', line 30

def build_options(argv)
  option_values = {}
  argv = option_parser.parse(argv, into: option_values)
  option_values = option_values.transform_keys { _1.to_s.tr("-", "_").to_sym }
  option_values[:token] ||= ENV.fetch("SLACK_API_TOKEN", nil)

  Slkecho::Options.new(option_values).tap do |opt|
    opt.message = fetch_message(argv)
  end
end

#fetch_message(argv) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/slkecho/option_parser.rb', line 41

def fetch_message(argv)
  if !argv.empty?
    argv.first
  elsif !$stdin.tty?
    $stdin.read.then { _1.empty? ? nil : _1 }
  end
end

#option_parserObject

rubocop:disable Metrics/MethodLength



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/slkecho/option_parser.rb', line 7

def option_parser # rubocop:disable Metrics/MethodLength
  @option_parser ||= ::OptionParser.new do |o|
    o.banner = "Usage: slkecho [options] message"
    o.program_name = "slkecho"
    o.version = Slkecho::VERSION
    o.on("--configure", "Configure Slack API token.")
    o.on("-c", "--channel CHANNEL", "Slack channel to post message.")
    o.on("-m", "--mention-by-email EMAIL", "Mention to user by email.")
    o.on("--username USERNAME", "Set user name for message.")
    o.on("--icon-url ICON_URL", "Set user icon image for message by URL.")
    o.on("--icon-emoji ICON_EMOJI", "Set user image for message by emoji.")
    o.on("--message-as-blocks", "Post message as blocks.")
    o.on("--token TOKEN", "Slack API token.")
  end
end

#parse(argv) ⇒ Object



23
24
25
26
27
28
# File 'lib/slkecho/option_parser.rb', line 23

def parse(argv)
  options = build_options(argv)
  validate_options(options)

  options
end

#validate_options(options) ⇒ Object



49
50
51
52
53
# File 'lib/slkecho/option_parser.rb', line 49

def validate_options(options)
  raise Slkecho::InvalidOptionError, options.error_message unless options.valid?

  true
end