Exception: Takagi::Errors::RegistryError

Inherits:
TakagiError
  • Object
show all
Defined in:
lib/takagi/errors.rb

Overview

Raised when registry operations fail

Instance Attribute Summary

Attributes inherited from TakagiError

#context, #suggestions

Class Method Summary collapse

Methods inherited from TakagiError

#initialize

Constructor Details

This class inherits a constructor from Takagi::Errors::TakagiError

Class Method Details

.already_registered(registry_name, key) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/takagi/errors.rb', line 125

def self.already_registered(registry_name, key)
  new(
    "#{key.inspect} is already registered in #{registry_name}",
    context: {
      registry: registry_name,
      key: key
    },
    suggestions: [
      "Use register(#{key.inspect}, value, overwrite: true) to replace",
      "Call unregister(#{key.inspect}) first, then register again",
      "Check if key is already registered with registered?(#{key.inspect})"
    ]
  )
end

.find_similar(input, candidates, threshold: 3) ⇒ Object

Simple Levenshtein distance for fuzzy matching



141
142
143
144
145
# File 'lib/takagi/errors.rb', line 141

def self.find_similar(input, candidates, threshold: 3)
  candidates.select do |candidate|
    levenshtein_distance(input, candidate) <= threshold
  end.sort_by { |c| levenshtein_distance(input, c) }
end

.levenshtein_distance(s, t) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/takagi/errors.rb', line 147

def self.levenshtein_distance(s, t)
  m = s.length
  n = t.length
  return m if n == 0
  return n if m == 0

  d = Array.new(m + 1) { Array.new(n + 1) }

  (0..m).each { |i| d[i][0] = i }
  (0..n).each { |j| d[0][j] = j }

  (1..n).each do |j|
    (1..m).each do |i|
      d[i][j] = if s[i - 1] == t[j - 1]
                  d[i - 1][j - 1]
                else
                  [d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + 1].min
                end
    end
  end

  d[m][n]
end

.not_found(registry_name, key, available_keys) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/takagi/errors.rb', line 111

def self.not_found(registry_name, key, available_keys)
  similar = find_similar(key.to_s, available_keys.map(&:to_s))

  new(
    "#{key.inspect} not found in #{registry_name}",
    context: {
      registry: registry_name,
      requested: key,
      available: available_keys.empty? ? "(empty registry)" : available_keys.inspect
    },
    suggestions: similar.empty? ? [] : ["Use #{similar.first.to_sym.inspect} instead?"]
  )
end