Module: Tina4::ImportHelper

Defined in:
lib/tina4/import_helper.rb

Defined Under Namespace

Modules: ConstMissing, RequireHook

Constant Summary collapse

FRAMEWORK_DIR =

The directory that holds the real framework files (lib/tina4/*.rb). Computed from this file's own location so it survives being loaded from a gem install path, a git checkout, or a worktree alike.

File.expand_path(__dir__).freeze

Class Method Summary collapse

Class Method Details

.close_matches(word, dictionary, max: 3) ⇒ Object

Return up to max close-match strings from dictionary for word. Uses stdlib DidYouMean::SpellChecker where available (Ruby 3.1+ ships it), and falls back to a small Levenshtein implementation otherwise.

Never raises: an empty dictionary or a blank word returns [].



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/tina4/import_helper.rb', line 64

def close_matches(word, dictionary, max: 3)
  list = Array(dictionary).map(&:to_s)
  return [] if list.empty? || word.to_s.empty?

  if defined?(DidYouMean::SpellChecker)
    suggestions = DidYouMean::SpellChecker.new(dictionary: list).correct(word.to_s)
    return suggestions.first(max) unless suggestions.nil? || suggestions.empty?
  end

  # Levenshtein fallback: rank by edit distance, keep the closest few
  # within a reasonable threshold so a truly wrong guess still returns [].
  scored = list.map { |candidate| [candidate, levenshtein(word.to_s, candidate)] }
  threshold = [(word.to_s.length / 3.0).ceil, 3].max
  scored.select { |_, distance| distance <= threshold }
        .sort_by { |candidate, distance| [distance, candidate] }
        .first(max)
        .map(&:first)
end

.installObject

Install both hooks. Idempotent: safe to call more than once (extra calls no-op). The framework boot in lib/tina4.rb calls this exactly once at the end of its own require chain.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/tina4/import_helper.rb', line 38

def install
  return if @installed

  # Load DidYouMean once, quietly. It ships with Ruby 3.1+ (the
  # framework's minimum), but never *fail* boot if it happens to be
  # absent: the close_matches Levenshtein fallback covers that case.
  begin
    require "did_you_mean"
  rescue LoadError
    # fall through to the Levenshtein path in close_matches
  end

  Tina4.singleton_class.prepend(ConstMissing)
  Kernel.prepend(RequireHook)
  @installed = true
end

.installed?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/tina4/import_helper.rb', line 55

def installed?
  @installed == true
end

.some_tina4_constants(limit = 5) ⇒ Object

A short, ordered sample of real Tina4 constants — used when nothing was close enough to suggest, so the reader still leaves with something to try.



86
87
88
# File 'lib/tina4/import_helper.rb', line 86

def some_tina4_constants(limit = 5)
  Tina4.constants.map(&:to_s).sort.first(limit)
end