Created
March 22, 2022 19:59
-
-
Save carlzulauf/eb34cec9d7fa919a9d8d66493df4bc76 to your computer and use it in GitHub Desktop.
A pry session that remembers
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
#!/usr/bin/env ruby | |
# Console script with saved data serialized into script body at bottom | |
# | |
# `Console#db` is serialized via YAML whenever the `save` method is called | |
# * YAML is placed after special `__END__` keyword | |
# * Script can access data after `__END__` via `DATA` constant | |
# Useful as a skeleton for one-off console scripts needing limited data storage | |
require 'pry' | |
require 'yaml' | |
class Console | |
attr_reader :script_path, :db | |
def initialize | |
@script_path = File.expand_path(__FILE__) | |
@db = defined?(DATA) ? YAML.load(DATA.read) : {} | |
end | |
def save(source: script_path, destination: script_path) | |
all_lines = File.readlines(source) | |
source_end = all_lines.index("__END__\n") | |
source_lines = source_end ? all_lines[0...source_end] : all_lines | |
data = @db&.any? ? "\n__END__\n#{@db.to_yaml}" : "" | |
File.write(destination, source_lines.join.strip + "\n" + data) | |
end | |
def clear! | |
@db = {} | |
save | |
end | |
end | |
Pry.start(Console.new) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment