Class: Keg::Relocation

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
keg_relocate.rb

Constant Summary collapse

RELOCATABLE_PATH_REGEX_PREFIX =
/(?<![a-zA-Z0-9])/.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRelocation

Returns a new instance of Relocation.



16
17
18
# File 'keg_relocate.rb', line 16

def initialize
  @replacement_map = {}
end

Class Method Details

.path_to_regex(path) ⇒ Regexp

Parameters:

Returns:

  • (Regexp)


53
54
55
56
57
58
59
60
61
# File 'keg_relocate.rb', line 53

def self.path_to_regex(path)
  path = case path
  when String
    Regexp.escape(path)
  when Regexp
    path.source
  end
  Regexp.new(RELOCATABLE_PATH_REGEX_PREFIX.source + path)
end

Instance Method Details

#add_replacement_pair(key, old_value, new_value, path: false) ⇒ void

This method returns an undefined value.

Parameters:

  • key (Symbol)
  • old_value (String, Regexp)
  • new_value (String)
  • path (Boolean) (defaults to: false)


26
27
28
29
# File 'keg_relocate.rb', line 26

def add_replacement_pair(key, old_value, new_value, path: false)
  old_value = self.class.path_to_regex(old_value) if path
  @replacement_map[key] = [old_value, new_value]
end

#freezeObject



20
21
22
23
# File 'keg_relocate.rb', line 20

def freeze
  @replacement_map.freeze
  super
end

#replace_text(text) ⇒ void

This method returns an undefined value.

Parameters:



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'keg_relocate.rb', line 37

def replace_text(text)
  replacements = @replacement_map.values.to_h

  sorted_keys = replacements.keys.sort_by do |key|
    key.is_a?(String) ? key.length : 999
  end.reverse

  any_changed = false
  sorted_keys.each do |key|
    changed = text.gsub!(key, replacements[key])
    any_changed ||= changed
  end
  any_changed
end

#replacement_pair_for(key) ⇒ Array<String, Regexp>

Parameters:

Returns:



32
33
34
# File 'keg_relocate.rb', line 32

def replacement_pair_for(key)
  @replacement_map.fetch(key)
end