Skip to content

Instantly share code, notes, and snippets.

@shreve
Created November 2, 2017 03:59
Show Gist options
  • Save shreve/0575b183f7c3f8e033f9f4bb7d2d3e21 to your computer and use it in GitHub Desktop.
Save shreve/0575b183f7c3f8e033f9f4bb7d2d3e21 to your computer and use it in GitHub Desktop.
Early Watson Idea
#!/usr/bin/env ruby
require 'io/console'
require_relative 'ansi'
class App
attr_accessor :input
attr_accessor :selection
class << self
attr_accessor :queries
end
self.queries = []
def initialize
@input = ''
@selection = 0
end
def run
IO.console.raw do
ANSI.clear_screen
ANSI.move_cursor(0, 0)
loop do
render
handle_input
end
end
end
def render
ANSI.clear_screen
ANSI.move_cursor(0, 0)
puts input_line
ANSI.move_cursor(1, 0)
results.each do |result|
puts result.join(': ')
print "\r"
end
ANSI.move_cursor(0, input_line.length)
end
def handle_input
char = $stdin.getc
case char
when "\u0003" # ctrl-c
ANSI.clear_screen
exit 0
when "\u007F" # backspace
self.input = input[0..-2]
else
input << char
end
end
def input_line
'------> ' << input
end
def results
return [] if input.empty?
App.queries.map do |query|
query.new(input).preview_text
end.compact
end
end
# This module contains helpers for various ansi-code operations
module ANSI
# ANSI color escape codes set the foreground and background colors.
# Forground color is a number between 30 and 37.
# Background color is a number between 40 and 47.
# The ones place represents the same color for both.
COLORS = [:black, :red, :green, :yellow, :blue, :magenta, :cyan, 'white', nil, :white].freeze
def self.clear_screen
$stdout.write "\e[2J"
end
def self.move_cursor(row, col)
$stdout.write "\e[#{row + 1};#{col + 1}H"
end
def self.color(text, fg: :white, bg: :black)
fg = COLORS.index(fg) + 30
bg = COLORS.index(bg) + 40
code = "\e[#{[fg, bg].compact.join(';')}m"
"#{code}#{text}\e[0m"
end
def self.reset
"\e[0m"
end
def self.size
win = IO.console.winsize
{
height: win[0],
width: win[1]
}
end
end
class Query
attr_reader :input
def initialize(input)
@input = input
end
def preview_text
res = result
[self.class.name, res] if res
end
def result
input
end
end
class Calc < Query
include Math
def result
begin
[input, eval(input + '.to_f')].join(' = ')
rescue Exception => _e
end
end
def pi
PI
end
def e
E
end
end
class Google < Query
end
class DuckDuckGo < Query
end
App.queries.push(Calc)
App.queries.push(Google)
App.queries.push(DuckDuckGo)
App.new.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment