Created
January 31, 2013 02:04
-
-
Save jschairb/4679308 to your computer and use it in GitHub Desktop.
Proof of Concept for storing command-line interaction in YAML files similar to VCR does with HTTP requests.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'logger' | |
require 'yaml' | |
class CommandsFile | |
FILE_PATH = File.join(File.dirname(__FILE__), "commands.yml") | |
def self.load | |
commands_file = new | |
commands_file.load | |
end | |
def self.write(text) | |
commands_file = new | |
commands_file.write(text) | |
end | |
def load | |
YAML.load_file(FILE_PATH) || [] | |
end | |
def write(text) | |
File.open(FILE_PATH, 'w') { |f| | |
f.write(YAML.dump(text)) | |
} | |
end | |
end | |
class Captures | |
attr_reader :captured_commands, :logger | |
def initialize(log_stream = STDOUT) | |
@captured_commands = CommandsFile.load | |
@logger = Logger.new(log_stream) | |
logger.formatter = proc do |severity, datetime, progname, msg| | |
"#{datetime.strftime("%y%m%e%H%M%S")}: #{msg}\n" | |
end | |
end | |
def create(command, output) | |
logger.debug("#create - `#{command}`") | |
new_command = { captured_at: Time.now, command: command, output: output } | |
captured_commands << new_command | |
CommandsFile.write(captured_commands) | |
new_command[:output] | |
end | |
def find(command) | |
logger.debug("#find - `#{command}`") | |
captured_commands.select { |c| c[:command] == command }.first | |
end | |
end | |
module CommandCapture | |
def `(command) | |
captures = Captures.new | |
captured = captures.find(command) | |
captured ? captured[:output] : captures.create(command, super) | |
end | |
end | |
Object.send(:include, CommandCapture) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
➜ tmp irb -I . -r 'command_capture' | |
irb(main):001:0> `date` | |
130130200203: #find - `date` | |
130130200203: #create - `date` | |
=> "Wed Jan 30 20:02:03 CST 2013\n" | |
irb(main):002:0> `df -h` | |
130130200217: #find - `df -h` | |
130130200217: #create - `df -h` | |
=> "Filesystem Size Used Avail Capacity Mounted on\n/dev/disk0s2 698Gi 76Gi 622Gi 11% /\ndevfs 184Ki 184Ki 0Bi 100% /dev\nmap -hosts 0Bi 0Bi 0Bi 100% /net\nmap auto_home 0Bi 0Bi 0Bi 100% /home\nmap -fstab 0Bi 0Bi 0Bi 100% /Network/Servers\n" | |
irb(main):003:0> `date` | |
130130200231: #find - `date` | |
=> "Wed Jan 30 20:02:03 CST 2013\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment