Skip to content

Instantly share code, notes, and snippets.

@carlzulauf
Created March 22, 2022 19:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlzulauf/eb34cec9d7fa919a9d8d66493df4bc76 to your computer and use it in GitHub Desktop.
Save carlzulauf/eb34cec9d7fa919a9d8d66493df4bc76 to your computer and use it in GitHub Desktop.
A pry session that remembers
#!/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