From 46ae0c0970d271c4b0cdef350405b5be9894e26c Mon Sep 17 00:00:00 2001 From: Tom de Bruijn Date: Mon, 27 Sep 2021 16:32:29 +0200 Subject: [PATCH] Move shell methods to a general helper The helpers that interact with the user will need to be called from outside of the `Cli` namespace in the future. I need classes loaded before the `Cli` classes to be able to require a module like the `Shell` one to access those methods. I've added `module_function` to the module. This makes it possible to call the methods on the module directly, without having to include the module. ``` Shell.ask_for_input Shell.required_input "Your name?" Shell.yes_or_no "Cake?" ``` --- lib/mono.rb | 1 + lib/mono/cli.rb | 34 +--------------------------------- lib/mono/cli/init.rb | 2 +- lib/mono/shell.rb | 37 +++++++++++++++++++++++++++++++++++++ 4 files changed, 40 insertions(+), 34 deletions(-) create mode 100644 lib/mono/shell.rb diff --git a/lib/mono.rb b/lib/mono.rb index 1182f6f..f925d04 100644 --- a/lib/mono.rb +++ b/lib/mono.rb @@ -39,6 +39,7 @@ def message end end +require "mono/shell" require "mono/version" require "mono/version_object" require "mono/version_promoter" diff --git a/lib/mono/cli.rb b/lib/mono/cli.rb index ed838ee..513c1ed 100644 --- a/lib/mono/cli.rb +++ b/lib/mono/cli.rb @@ -6,40 +6,8 @@ module Mono module Cli - module Helpers - def ask_for_input - value = $stdin.gets - value ? value.chomp : "" - rescue Interrupt - puts "\nExiting..." - exit 1 - end - - def required_input(prompt) - loop do - print prompt - value = ask_for_input - return value unless value.empty? - end - end - - def yes_or_no(prompt, options = {}) - loop do - print prompt - input = ask_for_input.strip - input = options[:default] if input.empty? && options[:default] - case input - when "y", "Y", "yes" - return true - when "n", "N", "no" - return false - end - end - end - end - class Base - include Helpers + include Shell include Command::Helper def initialize(options = {}) diff --git a/lib/mono/cli/init.rb b/lib/mono/cli/init.rb index 7822a64..6b28428 100644 --- a/lib/mono/cli/init.rb +++ b/lib/mono/cli/init.rb @@ -3,7 +3,7 @@ module Mono module Cli class Init - include Helpers + include Shell def execute config = {} diff --git a/lib/mono/shell.rb b/lib/mono/shell.rb new file mode 100644 index 0000000..4e63eae --- /dev/null +++ b/lib/mono/shell.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +module Mono + module Shell + module_function + + def ask_for_input + value = $stdin.gets + value ? value.chomp : "" + rescue Interrupt + puts "\nExiting..." + exit 1 + end + + def required_input(prompt) + loop do + print prompt + value = ask_for_input + return value unless value.empty? + end + end + + def yes_or_no(prompt, options = {}) + loop do + print prompt + input = ask_for_input.strip + input = options[:default] if input.empty? && options[:default] + case input + when "y", "Y", "yes" + return true + when "n", "N", "no" + return false + end + end + end + end +end