Skip to content

Instantly share code, notes, and snippets.

@v2e4lisp
Created August 19, 2014 10:29
Show Gist options
  • Save v2e4lisp/5f361628ebfd70d3a875 to your computer and use it in GitHub Desktop.
Save v2e4lisp/5f361628ebfd70d3a875 to your computer and use it in GitHub Desktop.
json repl for ruby
require 'readline'
module Repl
module Command
class PWD
def self.parse argv=nil
dir = Repl::Container.dirs.last
'/' + (dir ? dir.join('/') : '')
end
end
class CD
def self.parse argv
argv
end
end
class LS
def self.parse argv
raise Repl::Exception.new("ls error!")
end
end
class LoadJSON
def self.parse argv
raise Repl::Exception.new("load is not yet implemented!")
end
end
COMMANDS = {
:cd => CD,
:ls => LS,
:pwd => PWD,
:load => LoadJSON,
}
def self.run!(cmd)
cmd_name = cmd.first.to_sym
cmd_parser = COMMANDS[cmd_name] or
raise Repl::Exception.new "Command '#{cmd_name}' not found!"
cmd_parser.parse(cmd)
end
end
end
module Repl
class Exception < ::Exception; end
module Container
def self.dirs
@dirs ||= []
end
def self.jsons
@json ||= {}
end
def self.root
@root
end
def self.current_object
dirs.last.inject(root) {|a, e| a[e]}
end
end
module_function
def prompt
"[#{Repl::Command::PWD.parse}] > "
end
def start
while true do
cmd = Readline.readline(prompt, true)
break unless cmd
cmd = cmd.strip.split(/\s+/)
next if cmd.empty?
begin
result = Command.run!(cmd)
rescue Exception => ex
puts "input: #{ex.message}"
else
puts result
end
end
end
end
Repl.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment