Class: Rufio::CommandHistory

Inherits:
Object
  • Object
show all
Defined in:
lib/rufio/command_history.rb

Overview

コマンド履歴管理クラス

Constant Summary collapse

DEFAULT_MAX_SIZE =
1000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(history_file, max_size: DEFAULT_MAX_SIZE) ⇒ CommandHistory

初期化

Parameters:

  • history_file (String)

    履歴ファイルのパス

  • max_size (Integer) (defaults to: DEFAULT_MAX_SIZE)

    履歴の最大保存数



13
14
15
16
17
18
19
20
# File 'lib/rufio/command_history.rb', line 13

def initialize(history_file, max_size: DEFAULT_MAX_SIZE)
  @history_file = history_file
  @max_size = max_size
  @history = []
  @position = -1  # -1 = 最新の位置(履歴の外)

  load_from_file if File.exist?(@history_file)
end

Instance Attribute Details

#sizeObject (readonly)

履歴のサイズを取得



87
88
89
# File 'lib/rufio/command_history.rb', line 87

def size
  @size
end

Instance Method Details

#add(command) ⇒ Object

コマンドを履歴に追加

Parameters:

  • command (String)

    追加するコマンド



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rufio/command_history.rb', line 24

def add(command)
  # 空のコマンドは無視
  return if command.nil? || command.strip.empty?

  # 連続する重複は無視
  return if !@history.empty? && @history.last == command

  @history << command

  # 最大サイズを超えたら古いものを削除
  @history.shift if @history.size > @max_size

  # 位置をリセット
  reset_position
end

#nextString

次のコマンドを取得(下矢印キー相当)

Returns:

  • (String)

    次のコマンド、最新位置の場合は空文字列



61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/rufio/command_history.rb', line 61

def next
  return "" if @history.empty? || @position == -1

  # 一つ次に移動
  @position += 1

  # 最新位置を超えた場合は空文字列を返す
  if @position >= @history.size
    @position = -1
    return ""
  end

  @history[@position]
end

#previousString?

前のコマンドを取得(上矢印キー相当)

Returns:

  • (String, nil)

    前のコマンド、存在しない場合はnil



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rufio/command_history.rb', line 42

def previous
  return nil if @history.empty?

  # 初回は最後のコマンドを返す
  if @position == -1
    @position = @history.size - 1
    return @history[@position]
  end

  # これ以上前がない場合
  return nil if @position <= 0

  # 一つ前に移動
  @position -= 1
  @history[@position]
end

#reset_positionObject

位置をリセット(新しいコマンド入力時などに使用)



82
83
84
# File 'lib/rufio/command_history.rb', line 82

def reset_position
  @position = -1
end

#saveObject

履歴をファイルに保存



77
78
79
# File 'lib/rufio/command_history.rb', line 77

def save
  File.write(@history_file, @history.join("\n") + "\n")
end