module ZendeskAppsTools::Common

Public Class Methods

included(base) click to toggle source
# File lib/zendesk_apps_tools/common.rb, line 27
def self.included(base)
  base.extend(ClassMethods)
end

Public Instance Methods

get_password_from_stdin(prompt) click to toggle source
# File lib/zendesk_apps_tools/common.rb, line 60
def get_password_from_stdin(prompt)
  error_or_default_if_unattended(prompt) do
    password = ask(prompt, echo: false)
    say ''
    password
  end
end
get_value_from_stdin(prompt, opts = {}) click to toggle source
# File lib/zendesk_apps_tools/common.rb, line 40
def get_value_from_stdin(prompt, opts = {})
  error_or_default_if_unattended(prompt, opts) do
    options = {
      valid_regex: opts[:allow_empty] ? /^.*$/ : /\S+/,
      error_msg: 'Invalid, try again:',
      allow_empty: false
    }.merge(opts)

    thor_options = { default: options[:default] }

    while input = ask(prompt, thor_options)
      return '' if options[:allow_empty] && input.empty?
      break if input.to_s =~ options[:valid_regex]
      say_error options[:error_msg]
    end

    input
  end
end
json_or_die(value) click to toggle source
# File lib/zendesk_apps_tools/common.rb, line 68
def json_or_die(value)
  require 'json'
  JSON.parse(value)
rescue JSON::ParserError
  say_error_and_exit "\"#{value}\" is an invalid JSON."
end
say_error(msg) click to toggle source
# File lib/zendesk_apps_tools/common.rb, line 36
def say_error(msg)
  say msg, :red
end
say_error_and_exit(msg) click to toggle source
# File lib/zendesk_apps_tools/common.rb, line 31
def say_error_and_exit(msg)
  say_error msg
  exit 1
end

Private Instance Methods

error_or_default_if_unattended(prompt, opts = {}) { || ... } click to toggle source
# File lib/zendesk_apps_tools/common.rb, line 77
def error_or_default_if_unattended(prompt, opts = {})
  if options[:unattended]
    return opts[:default] if opts.key? :default
    say_error 'Would have prompted for a value interactively, but ZAT is not listening to keyboard input.'
    say_error_and_exit prompt
  else
    yield
  end
end