Module: CommandSearch::Aliaser
- Defined in:
- lib/command_search/aliaser.rb
Class Method Summary collapse
- .alias(query, aliases) ⇒ Object
- .alias_item(query, alias_key, alias_value) ⇒ Object
- .build_regex(str) ⇒ Object
- .opens_quote?(str) ⇒ Boolean
Class Method Details
.alias(query, aliases) ⇒ Object
42 43 44 |
# File 'lib/command_search/aliaser.rb', line 42 def alias(query, aliases) aliases.reduce(query) { |q, (k, v)| alias_item(q, k, v) } 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 38 39 40 |
# File 'lib/command_search/aliaser.rb', line 19 def alias_item(query, alias_key, alias_value) if alias_key.is_a?(Regexp) pattern = alias_key else pattern = build_regex(alias_key.to_s) end current_match = query[pattern] return query unless current_match offset = Regexp.last_match.offset(0) head = query[0...offset.first] tail = alias_item(query[offset.last..-1], alias_key, alias_value) if opens_quote?(head) replacement = current_match else if alias_value.is_a?(String) replacement = alias_value elsif alias_value.is_a?(Proc) replacement = alias_value.call(current_match).to_s end end head + replacement + tail 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 |
.opens_quote?(str) ⇒ Boolean
11 12 13 14 15 16 17 |
# File 'lib/command_search/aliaser.rb', line 11 def opens_quote?(str) while str[/".*"/] || str[/'.*'/] mark = str[/["']/] str.sub(/#{mark}.*#{mark}/, '') end str[/"/] || str[/\B'/] end |