Skip to content

Instantly share code, notes, and snippets.

@equivalent
Last active October 16, 2019 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save equivalent/5a428eb71e1f511e2a352b3865898d87 to your computer and use it in GitHub Desktop.
Save equivalent/5a428eb71e1f511e2a352b3865898d87 to your computer and use it in GitHub Desktop.
copy-paste verison of Ruby Inputs gem

This is copy-paste version of Inputs gem

This is helpfull if you just want to paste the Inputs gem functionality to a Ruby script when library install (gem install inputs or bunde install) is not an option.

Just Copy-Paste the code bellow to your script and you'll have all the features of Inputs gem

Color prompt

For more color options check https://gist.github.com/equivalent/74b1dec423f186c6e594f00b9aacff10

Issues

Any issue with this Gist ? Please raise an issue in Inputs gem: https://github.com/equivalent/inputs

Discussion & Questions:

Comment bellow or reply to this Reddit thread

class String; def green; "\e[#{32}m#{self}\e[0m"; end; end # For more colors check https://gist.github.com/equivalent/74b1dec423f186c6e594f00b9aacff10
module Inputs
def self.yn(question)
begin
puts "#{question} [y/n]".green
input = STDIN.gets.chomp
end until %w(y n).include?(input)
case input
when 'y'; true
when 'n'; false
end
end
def self.name(question)
puts "#{question}".green
name = STDIN.gets
name = name.chomp
puts name.green
name
end
def self.name!(question)
puts "#{question}".green
name = STDIN.gets
name = name.chomp
if name != ''
puts name.green
name
end
end
def self.text(question)
puts "#{question}".green
txt = ''; STDIN.each_line {|l| txt = txt + l }; txt
puts txt.green
txt
end
def self.names(question)
puts "#{question} (Comma separated)".green
names = STDIN.gets.chomp.split(',').map(&:strip)
puts names.join(' & ').green
names
end
def self.pick(options, question: "Please choose:", option_output_eval: ->(key, option) { " Press #{key} for \"#{option}\"" })
option_map = options.map(&:to_s).uniq.map.with_index { |x, i| [i+1, x] }.to_h
begin
puts "#{question}".green
option_map.each { |key, option| puts "#{option_output_eval.call(key, option)}".green }
input = STDIN.gets.chomp.to_i
end until option_map.keys.include?(input)
option_map.fetch(input)
end
end
p Inputs.yn('Do you want a candy?')
p Inputs.name('What is your name ?')
p Inputs.name!('What is your favorite color ?')
p Inputs.names('What are the names of your parents')
p Inputs.pick(['car', 'dog', 'snake'])
p Inputs.text('Tell me your story')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment