Module: CommandSearch::Aliaser

Defined in:
lib/command_search/aliaser.rb

Class Method Summary collapse

Class Method Details

.alias(query, aliases) ⇒ Object



30
31
32
33
34
35
# File 'lib/command_search/aliaser.rb', line 30

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, key, val) ⇒ Object



19
20
21
22
23
24
25
26
27
28
# File 'lib/command_search/aliaser.rb', line 19

def alias_item!(query, key, val)
  if key.is_a?(String) || key.is_a?(Symbol)
    key = build_regex(key)
  end
  query.gsub!(key) do |match|
    next match if quotes?(query, Regexp.last_match.offset(0))
    next val.call(match) if val.is_a?(Proc)
    val
  end
end

.build_regex(str) ⇒ Object



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

def build_regex(str)
  head = '(?<=^|[^:\w])'
  tail = '(?=$|\W)'
  Regexp.new(head + Regexp.escape(str) + tail, '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