Sha256: 766bbe7bd656aa6571cebc656dea642522754d19d5ba2cfe68a25ff64cb8194e

Contents?: true

Size: 1020 Bytes

Versions: 1

Compression:

Stored size: 1020 Bytes

Contents

module Interactive
  class Question
    attr_accessor :question, :options

    def initialize(&block)
      yield self
    end

    def ask_and_wait_for_valid_response(&block)
      resp = NullResponse.new

      while resp.invalid? do
        puts "#{question} #{shortcuts_string}"
        resp = Interactive::Response.new(options)
        puts shortcuts_meanings if resp.invalid?

        yield resp
      end
    end

    class NullResponse
      def invalid?
        true
      end
    end

    private

    def response
      STDIN.gets.chomp
    end

    def shortcuts_meanings
      options.inject("") { |accum, opt| "#{accum}  #{opt[0]} -- #{opt}\n"}
    end

    def options_first_chars
      options.inject("") { |accum, opt| "#{accum}#{opt[0]}/" }
    end

    def shortcuts_string
      "[#{options_first_chars_without_last_slash(options_first_chars)}]"
    end

    def options_first_chars_without_last_slash(options_first_chars)
      options_first_chars[0..options_first_chars.length-2]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
interactive-0.0.0 lib/interactive/question.rb