Module: CommandSearch::Aliaser

Defined in:
lib/command_search/aliaser.rb

Class Method Summary collapse

Class Method Details

.alias(query, aliases) ⇒ Object



39
40
41
42
43
44
# File 'lib/command_search/aliaser.rb', line 39

def alias(query, aliases)
  return query unless aliases.any?
  out = query.dup
  aliases.each { |(k, v)| alias_item(out, k, v) }
  out
end

.alias_item(query, alias_key, alias_value) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/command_search/aliaser.rb', line 19

def alias_item(query, alias_key, alias_value)
  return query unless alias_value.is_a?(String) || alias_value.is_a?(Proc)
  if alias_key.is_a?(Regexp)
    pattern = alias_key
  elsif alias_key.is_a?(String)
    pattern = build_regex(alias_key)
  else
    return query
  end
  query.gsub!(pattern) do |match|
    next match if quotes?(query, Regexp.last_match.offset(0))
    if alias_value.is_a?(String)
      alias_value
    elsif alias_value.is_a?(Proc)
      alias_value.call(match).to_s
    end
  end
  query
end

.build_regex(str) ⇒ Object



5
6
7
8
9
# File 'lib/command_search/aliaser.rb', line 5

def build_regex(str)
  head_border = '(?<=^|[^:\w])'
  tail_border = '(?=$|\W)'
  Regexp.new(head_border + Regexp.escape(str) + tail_border, 'i')
end

.quotes?(str, offset) ⇒ Boolean

Returns:



11
12
13
14
15
16
17
# File 'lib/command_search/aliaser.rb', line 11

def quotes?(str, offset)
  head = str[0...offset[0]]
  tail = str[offset[1]..-1]
  return true if head.count("'").odd? && tail.count("'").odd?
  return true if head.count('"').odd? && tail.count('"').odd?
  false
end