Skip to content

Commit

Permalink
Move shell methods to a general helper
Browse files Browse the repository at this point in the history
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?"
```
  • Loading branch information
tombruijn committed Sep 27, 2021
1 parent 616571e commit 46ae0c0
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 34 deletions.
1 change: 1 addition & 0 deletions lib/mono.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def message
end
end

require "mono/shell"
require "mono/version"
require "mono/version_object"
require "mono/version_promoter"
Expand Down
34 changes: 1 addition & 33 deletions lib/mono/cli.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {})
Expand Down
2 changes: 1 addition & 1 deletion lib/mono/cli/init.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
module Mono
module Cli
class Init
include Helpers
include Shell

def execute
config = {}
Expand Down
37 changes: 37 additions & 0 deletions lib/mono/shell.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 46ae0c0

Please sign in to comment.