Class: Yorishiro::InputHistory
- Inherits:
-
Object
- Object
- Yorishiro::InputHistory
- Defined in:
- lib/yorishiro/input_history.rb
Overview
Persists the Reline input-line history to disk so that past prompts can be recalled with the up arrow across sessions. The history file lives under the launch directory (cwd), so each project keeps its own history. Entries are stored as a JSON array of strings; JSON is used (rather than newline- separated text) because a single multi-line input is one entry containing embedded newlines.
Constant Summary collapse
- DIR_NAME =
".yorishiro"- FILE_NAME =
"history.json"- MAX_ENTRIES =
Cap the on-disk history so it does not grow without bound.
1000
Instance Attribute Summary collapse
-
#path ⇒ Object
readonly
Returns the value of attribute path.
Instance Method Summary collapse
-
#initialize(dir: Dir.pwd, max_entries: MAX_ENTRIES) ⇒ InputHistory
constructor
A new instance of InputHistory.
-
#load ⇒ Object
Populate Reline::HISTORY from the saved file.
-
#save ⇒ Object
Write the current Reline::HISTORY (trimmed to the most recent
max_entries) to disk as a JSON array.
Constructor Details
#initialize(dir: Dir.pwd, max_entries: MAX_ENTRIES) ⇒ InputHistory
Returns a new instance of InputHistory.
19 20 21 22 |
# File 'lib/yorishiro/input_history.rb', line 19 def initialize(dir: Dir.pwd, max_entries: MAX_ENTRIES) @path = File.join(dir, DIR_NAME, FILE_NAME) @max_entries = max_entries end |
Instance Attribute Details
#path ⇒ Object (readonly)
Returns the value of attribute path.
24 25 26 |
# File 'lib/yorishiro/input_history.rb', line 24 def path @path end |
Instance Method Details
#load ⇒ Object
Populate Reline::HISTORY from the saved file. No-op if the file is absent or unreadable/corrupt (a broken history file should never block startup).
28 29 30 31 32 33 34 35 36 37 |
# File 'lib/yorishiro/input_history.rb', line 28 def load return unless File.exist?(@path) entries = JSON.parse(File.read(@path)) return unless entries.is_a?(Array) entries.each { |entry| Reline::HISTORY << entry.to_s } rescue JSON::ParserError, SystemCallError nil end |
#save ⇒ Object
Write the current Reline::HISTORY (trimmed to the most recent
max_entries) to disk as a JSON array.
41 42 43 44 45 46 47 |
# File 'lib/yorishiro/input_history.rb', line 41 def save FileUtils.mkdir_p(File.dirname(@path)) entries = Reline::HISTORY.to_a.last(@max_entries) File.write(@path, JSON.generate(entries)) rescue SystemCallError nil end |