Class: String
- Inherits:
-
Object
- Object
- String
- Includes:
- Doing::Color
- Defined in:
- lib/doing/string.rb,
lib/doing/string_chronify.rb,
lib/doing/template_string.rb
Overview
Chronify methods for strings
Direct Known Subclasses
Constant Summary
Constants included from Doing::Color
Doing::Color::ATTRIBUTES, Doing::Color::ATTRIBUTE_NAMES, Doing::Color::COLORED_REGEXP
Instance Method Summary collapse
-
#add_at ⇒ String
Add @ prefix to string if needed, maintains +/- prefix.
-
#add_tags(tags, remove: false) ⇒ String
The tagged string.
- #add_tags!(tags, remove: false) ⇒ Object
-
#cap_first ⇒ Object
Capitalize on the first character on string.
-
#chronify(**options) ⇒ DateTime
Converts input string into a Time object when input takes on the following formats: - interval format e.g.
-
#chronify_qty ⇒ Integer
Converts simple strings into seconds that can be added to a Time object.
-
#clean_unlinked_urls ⇒ Object
Clean up unlinked
. -
#compress ⇒ Object
Compress multiple spaces to single space.
- #compress! ⇒ Object
-
#dedup_tags ⇒ Object
Remove duplicate tags, leaving only first occurrence.
- #dedup_tags! ⇒ Object
-
#expand_date_tags(additional_tags = nil) ⇒ Object
Convert (chronify) natural language dates within configured date tags (tags whose value is expected to be a date).
- #highlight_search(search, distance: nil, negate: false, case_type: nil) ⇒ Object
- #highlight_search!(search, distance: nil, negate: false, case_type: nil) ⇒ Object
-
#highlight_tags(color = 'yellow', last_color: nil) ⇒ String
Colorize @tags with ANSI escapes.
- #highlight_tags!(color = 'yellow', last_color: nil) ⇒ Object
-
#ignore? ⇒ Boolean
Test if line should be ignored.
- #ignore_case(search, case_type) ⇒ Object
- #is_range? ⇒ Boolean
-
#is_rx? ⇒ Boolean
Determines if receiver is surrounded by slashes or starts with single quote.
-
#last_color ⇒ String
Returns the last escape sequence from a string.
-
#link_urls(**opt) ⇒ Object
Turn raw urls into HTML links.
- #link_urls!(**opt) ⇒ Object
-
#normalize_age(default = :newest) ⇒ Symbol
Convert an age string to a qualified type.
- #normalize_age!(default = :newest) ⇒ Object
-
#normalize_bool(default = :and) ⇒ Object
Convert a boolean string to a symbol.
- #normalize_bool!(default = :and) ⇒ Object
-
#normalize_case(default = :smart) ⇒ Object
Convert a case sensitivity string to a symbol.
- #normalize_case! ⇒ Object
-
#normalize_matching(default = :pattern) ⇒ Object
Convert a matching configuration string to a symbol.
- #normalize_matching!(default = :pattern) ⇒ Object
- #normalize_order(default = 'asc') ⇒ Object
-
#normalize_order!(default = 'asc') ⇒ String
Convert a sort order string to a qualified type.
-
#normalize_trigger ⇒ String
Adds ?: to any parentheticals in a regular expression to avoid match groups.
- #normalize_trigger! ⇒ Object
-
#remove_at ⇒ String
Removes @ prefix if needed, maintains +/- prefix.
-
#remove_self_links ⇒ Object
Remove
formatting. -
#replace_qualified_urls(**options) ⇒ Object
Replace qualified urls.
-
#set_type(kind = nil) ⇒ Object
Convert a string value to an appropriate type.
- #simple_wrap(width) ⇒ Object
-
#split_date_range ⇒ Array<DateTime>
Splits a range string and returns an array of DateTime objects as [start, end].
-
#tag(tag, value: nil, remove: false, rename_to: nil, regex: false, single: false, force: false) ⇒ String
Add, rename, or remove a tag.
-
#tag!(tag, **options) ⇒ Object
Add, rename, or remove a tag in place.
-
#time_string(format: :dhm) ⇒ Object
Convert DD:HH:MM to a natural language string.
- #to_bool ⇒ Object
-
#to_p(number) ⇒ Object
Pluralize a string based on quantity.
- #to_phrase_query(query) ⇒ Object
-
#to_rx(distance: nil, case_type: nil) ⇒ Regexp
Convert string to fuzzy regex.
-
#to_seconds ⇒ Integer
Convert DD:HH:MM to seconds.
-
#to_tags ⇒ Array
Convert a list of tags to an array.
-
#truncate(len, ellipsis: '...') ⇒ Object
Truncate to nearest word.
- #truncate!(len, ellipsis: '...') ⇒ Object
-
#truncmiddle(len, ellipsis: '...') ⇒ Object
Truncate string in the middle.
- #truncmiddle!(len, ellipsis: '...') ⇒ Object
-
#truthy? ⇒ Boolean
Test string for truthiness (0, "f", "false", "n", "no" all return false, case insensitive, otherwise true).
-
#uncolor ⇒ Object
Remove color escape codes.
- #uncolor! ⇒ Object
-
#validate_color ⇒ String
private
Extract the longest valid color from a string.
-
#wildcard_to_rx ⇒ String
Convert ? and * wildcards to regular expressions.
-
#wrap(len, pad: 0, indent: ' ', offset: 0, prefix: '', color: '', after: '', reset: '', pad_first: false) ⇒ Object
Wrap string at word breaks, respecting tags.
Methods included from Doing::Color
attributes, coloring?, #support?
Instance Method Details
#add_at ⇒ String
Add @ prefix to string if needed, maintains +/- prefix
460 461 462 |
# File 'lib/doing/string.rb', line 460 def add_at strip.sub(/^([+-]*)@?/, '\1@') end |
#add_tags(tags, remove: false) ⇒ String
Returns the tagged string.
492 493 494 495 496 497 |
# File 'lib/doing/string.rb', line 492 def (, remove: false) title = self.dup = . .each { |tag| title.tag!(tag, remove: remove) } title end |
#add_tags!(tags, remove: false) ⇒ Object
500 501 502 |
# File 'lib/doing/string.rb', line 500 def (, remove: false) replace (, remove: remove) end |
#cap_first ⇒ Object
Capitalize on the first character on string
299 300 301 302 303 |
# File 'lib/doing/string.rb', line 299 def cap_first sub(/^\w/) do |m| m.upcase end end |
#chronify(**options) ⇒ DateTime
Converts input string into a Time object when input takes on the following formats: - interval format e.g. '1d2h30m', '45m' etc. - a semantic phrase e.g. 'yesterday 5:30pm' - a strftime e.g. '2016-03-15 15:32:04 PDT'
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/doing/string_chronify.rb', line 27 def chronify(**) now = Time.now raise Errors::InvalidTimeExpression, "Invalid time expression #{inspect}" if to_s.strip == '' secs_ago = if match(/^(\d+)$/) # plain number, assume minutes Regexp.last_match(1).to_i * 60 elsif (m = match(/^(?:(?<day>\d+)d)? *(?:(?<hour>\d+)h)? *(?:(?<min>\d+)m)?$/i)) # day/hour/minute format e.g. 1d2h30m [[m['day'], 24 * 3600], [m['hour'], 3600], [m['min'], 60]].map { |qty, secs| qty ? (qty.to_i * secs) : 0 }.reduce(0, :+) end if secs_ago res = now - secs_ago Doing.logger.debug('Parser:', %(date/time string "#{self}" interpreted as #{res} (#{secs_ago} seconds ago))) else date_string = dup date_string = 'today' if date_string.match(REGEX_DAY) && now.strftime('%a') =~ /^#{Regexp.last_match(1)}/i date_string = "#{options[:context].to_s} #{date_string}" if date_string =~ REGEX_TIME && [:context] res = Chronic.parse(date_string, { guess: .fetch(:guess, :begin), context: .fetch(:future, false) ? :future : :past, ambiguous_time_range: 8 }) Doing.logger.debug('Parser:', %(date/time string "#{self}" interpreted as #{res})) end res end |
#chronify_qty ⇒ Integer
Converts simple strings into seconds that can be added to a Time object
Input string can be HH:MM or XX[[XXhm][XXm]] (1d2h30m, 45m, 1.5d, 1h20m, etc.)
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/doing/string_chronify.rb', line 70 def chronify_qty minutes = 0 case self.strip when /^(\d+):(\d\d)$/ minutes += Regexp.last_match(1).to_i * 60 minutes += Regexp.last_match(2).to_i when /^(\d+(?:\.\d+)?)([hmd])?/ scan(/(\d+(?:\.\d+)?)([hmd])?/).each do |m| amt = m[0] type = m[1].nil? ? 'm' : m[1] minutes += case type.downcase when 'm' amt.to_i when 'h' (amt.to_f * 60).round when 'd' (amt.to_f * 60 * 24).round else 0 end end end minutes * 60 end |
#clean_unlinked_urls ⇒ Object
Clean up unlinked
686 687 688 689 690 691 692 693 694 695 |
# File 'lib/doing/string.rb', line 686 def clean_unlinked_urls gsub(/<(\w+:.*?)>/) do |match| m = Regexp.last_match if m[1] =~ /<a href/ match else %(<a href="#{m[1]}" title="Link to #{m[1]}">[link]</a>) end end end |
#compress ⇒ Object
Compress multiple spaces to single space
70 71 72 |
# File 'lib/doing/string.rb', line 70 def compress gsub(/ +/, ' ').strip end |
#compress! ⇒ Object
74 75 76 |
# File 'lib/doing/string.rb', line 74 def compress! replace compress end |
#dedup_tags ⇒ Object
Remove duplicate tags, leaving only first occurrence
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 |
# File 'lib/doing/string.rb', line 586 def title = dup = title.scan(/(?<=\A| )(@(\S+?)(\([^)]+\))?)(?= |\Z)/).uniq .each do |tag| found = false title.gsub!(/( |^)#{tag[1]}(\([^)]+\))?(?= |$)/) do |m| if found '' else found = true m end end end title end |
#dedup_tags! ⇒ Object
604 605 606 |
# File 'lib/doing/string.rb', line 604 def replace end |
#expand_date_tags(additional_tags = nil) ⇒ Object
Convert (chronify) natural language dates within configured date tags (tags whose value is expected to be a date). Modifies string in place.
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
# File 'lib/doing/string_chronify.rb', line 130 def ( = nil) iso_rx = /\d{4}-\d\d-\d\d \d\d:\d\d/ = [ 'start(?:ed)?', 'beg[ia]n', 'done', 'finished', 'completed?', 'waiting', 'defer(?:red)?' ] if = = .split(/ *, */) if .is_a?(String) .map! do |tag| tag.sub(/^@/, '').gsub(/\((?!\?:)(.*?)\)/, '(?:\1)').strip end .concat().uniq! end done_rx = /(?<=^| )@(?<tag>#{watch_tags.join('|')})\((?<date>.*?)\)/i gsub!(done_rx) do m = Regexp.last_match t = m['tag'] d = m['date'] future = t =~ /^(done|complete)/ ? false : true parsed_date = d =~ iso_rx ? Time.parse(d) : d.chronify(guess: :begin, future: future) parsed_date.nil? ? m[0] : "@#{t}(#{parsed_date.strftime('%F %R')})" end end |
#highlight_search(search, distance: nil, negate: false, case_type: nil) ⇒ Object
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
# File 'lib/doing/string.rb', line 119 def highlight_search(search, distance: nil, negate: false, case_type: nil) out = dup prefs = Doing.config.settings['search'] || {} matching = prefs.fetch('matching', 'pattern').normalize_matching distance ||= prefs.fetch('distance', 3).to_i case_type ||= prefs.fetch('case', 'smart').normalize_case if search.is_rx? || matching == :fuzzy rx = search.to_rx(distance: distance, case_type: case_type) out.gsub!(rx) { |m| m.bgyellow.black } else query = to_phrase_query(search.strip) if query[:must].nil? && query[:must_not].nil? query[:must] = query[:should] query[:should] = [] end qs = [] qs.concat(query[:must]) if query[:must] qs.concat(query[:should]) if query[:should] qs.each do |s| rx = Regexp.new(s.wildcard_to_rx, ignore_case(s, case_type)) out.gsub!(rx) { |m| m.bgyellow.black } end end out end |
#highlight_search!(search, distance: nil, negate: false, case_type: nil) ⇒ Object
115 116 117 |
# File 'lib/doing/string.rb', line 115 def highlight_search!(search, distance: nil, negate: false, case_type: nil) replace highlight_search(search, distance: distance, negate: negate, case_type: case_type) end |
#highlight_tags(color = 'yellow', last_color: nil) ⇒ String
Colorize @tags with ANSI escapes
90 91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/doing/string.rb', line 90 def (color = 'yellow', last_color: nil) unless last_color escapes = scan(/(\e\[[\d;]+m)[^\e]+@/) color = color.split(' ') unless color.is_a?(Array) tag_color = color.each_with_object([]) { |c, arr| arr << Doing::Color.send(c) }.join('') last_color = if !escapes.empty? (escapes.count > 1 ? escapes[-2..-1] : [escapes[-1]]).map { |v| v[0] }.join('') else Doing::Color.default end end gsub(/(\s|m)(@[^ ("']+)/, "\\1#{tag_color}\\2#{last_color}") end |
#highlight_tags!(color = 'yellow', last_color: nil) ⇒ Object
79 80 81 |
# File 'lib/doing/string.rb', line 79 def (color = 'yellow', last_color: nil) replace (color) end |
#ignore? ⇒ Boolean
Test if line should be ignored
152 153 154 155 |
# File 'lib/doing/string.rb', line 152 def ignore? line = self line =~ /^#/ || line =~ /^\s*$/ end |
#ignore_case(search, case_type) ⇒ Object
111 112 113 |
# File 'lib/doing/string.rb', line 111 def ignore_case(search, case_type) (case_type == :smart && search !~ /[A-Z]/) || case_type == :ignore end |
#is_range? ⇒ Boolean
164 165 166 |
# File 'lib/doing/string_chronify.rb', line 164 def is_range? self =~ / (to|through|thru|(un)?til|-+) / end |
#is_rx? ⇒ Boolean
Determines if receiver is surrounded by slashes or starts with single quote
14 15 16 |
# File 'lib/doing/string.rb', line 14 def is_rx? self =~ %r{(^/.*?/$|^')} end |
#last_color ⇒ String
Returns the last escape sequence from a string.
Actually returns all escape codes, with the assumption that the result of inserting them will generate the same color as was set at the end of the string. Because you can send modifiers like dark and bold separate from color codes, only using the last code may not render the same style.
619 620 621 |
# File 'lib/doing/string.rb', line 619 def last_color scan(/\e\[[\d;]+m/).join('') end |
#link_urls(**opt) ⇒ Object
Turn raw urls into HTML links
:html (default)
631 632 633 634 635 636 637 638 639 640 |
# File 'lib/doing/string.rb', line 631 def link_urls(**opt) fmt = opt.fetch(:format, :html) return self unless fmt str = dup str = str.remove_self_links if fmt == :markdown str.replace_qualified_urls(format: fmt).clean_unlinked_urls end |
#link_urls!(**opt) ⇒ Object
643 644 645 646 |
# File 'lib/doing/string.rb', line 643 def link_urls!(**opt) fmt = opt.fetch(:format, :html) replace link_urls(format: fmt) end |
#normalize_age(default = :newest) ⇒ Symbol
Convert an age string to a qualified type
320 321 322 323 324 325 326 327 328 329 |
# File 'lib/doing/string.rb', line 320 def normalize_age(default = :newest) case self when /^o/i :oldest when /^n/i :newest else default end end |
#normalize_age!(default = :newest) ⇒ Object
332 333 334 |
# File 'lib/doing/string.rb', line 332 def normalize_age!(default = :newest) replace normalize_age(default) end |
#normalize_bool(default = :and) ⇒ Object
Convert a boolean string to a symbol
384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
# File 'lib/doing/string.rb', line 384 def normalize_bool(default = :and) case self when /(and|all)/i :and when /(any|or)/i :or when /(not|none)/i :not when /^p/i :pattern else default.is_a?(Symbol) ? default : default.normalize_bool end end |
#normalize_bool!(default = :and) ⇒ Object
400 401 402 |
# File 'lib/doing/string.rb', line 400 def normalize_bool!(default = :and) replace normalize_bool(default) end |
#normalize_case(default = :smart) ⇒ Object
Convert a case sensitivity string to a symbol
361 362 363 364 365 366 367 368 369 370 371 372 |
# File 'lib/doing/string.rb', line 361 def normalize_case(default = :smart) case self when /^(c|sens)/i :sensitive when /^i/i :ignore when /^s/i :smart else default.is_a?(Symbol) ? default : default.normalize_case end end |
#normalize_case! ⇒ Object
375 376 377 |
# File 'lib/doing/string.rb', line 375 def normalize_case! replace normalize_case end |
#normalize_matching(default = :pattern) ⇒ Object
Convert a matching configuration string to a symbol
412 413 414 415 416 417 418 419 420 421 422 423 |
# File 'lib/doing/string.rb', line 412 def normalize_matching(default = :pattern) case self when /^f/i :fuzzy when /^p/i :pattern when /^e/i :exact else default.is_a?(Symbol) ? default : default.normalize_matching end end |
#normalize_matching!(default = :pattern) ⇒ Object
426 427 428 |
# File 'lib/doing/string.rb', line 426 def normalize_matching!(default = :pattern) replace normalize_bool(default) end |
#normalize_order(default = 'asc') ⇒ Object
345 346 347 348 349 350 351 352 353 354 |
# File 'lib/doing/string.rb', line 345 def normalize_order(default = 'asc') case self when /^a/i 'asc' when /^d/i 'desc' else default end end |
#normalize_order!(default = 'asc') ⇒ String
Convert a sort order string to a qualified type
341 342 343 |
# File 'lib/doing/string.rb', line 341 def normalize_order!(default = 'asc') replace normalize_order(default) end |
#normalize_trigger ⇒ String
Adds ?: to any parentheticals in a regular expression to avoid match groups
436 437 438 |
# File 'lib/doing/string.rb', line 436 def normalize_trigger gsub(/\((?!\?:)/, '(?:').downcase end |
#normalize_trigger! ⇒ Object
441 442 443 |
# File 'lib/doing/string.rb', line 441 def normalize_trigger! replace normalize_trigger end |
#remove_at ⇒ String
Removes @ prefix if needed, maintains +/- prefix
469 470 471 |
# File 'lib/doing/string.rb', line 469 def remove_at strip.sub(/^([+-]*)@?/, '\1') end |
#remove_self_links ⇒ Object
Remove
649 650 651 652 653 654 655 656 657 658 |
# File 'lib/doing/string.rb', line 649 def remove_self_links gsub(/<(.*?)>/) do |match| m = Regexp.last_match if m[1] =~ /^https?:/ m[1] else match end end end |
#replace_qualified_urls(**options) ⇒ Object
Replace qualified urls
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 |
# File 'lib/doing/string.rb', line 661 def replace_qualified_urls(**) fmt = .fetch(:format, :html) gsub(%r{(?mi)(?x: (?<!["'\[(\\]) (?<protocol>(?:http|https)://) (?<domain>[\w\-]+(?:\.[\w\-]+)+) (?<path>[\w\-.,@?^=%&;:/~+#]*[\w\-@^=%&;/~+#])? )}) do |_match| m = Regexp.last_match url = "#{m['domain']}#{m['path']}" proto = m['protocol'].nil? ? 'http://' : m['protocol'] case fmt when :terminal TTY::Link.link_to("#{proto}#{url}", "#{proto}#{url}") when :html %(<a href="#{proto}#{url}" title="Link to #{m['domain']}">[#{url}]</a>) when :markdown "[#{url}](#{proto}#{url})" else m[0] end end end |
#set_type(kind = nil) ⇒ Object
Convert a string value to an appropriate type. If kind is not specified, '[one, two]' becomes an Array, '1' becomes Integer, '1.5' becomes Float, 'true' or 'yes' becomes TrueClass, 'false' or 'no' becomes FalseClass.
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 |
# File 'lib/doing/string.rb', line 718 def set_type(kind = nil) if kind case kind.to_s when /^a/i gsub(/^\[ *| *\]$/, '').split(/ *, */) when /^i/i to_i when /^(fa|tr)/i to_bool when /^f/i to_f when /^sy/i sub(/^:/, '').to_sym when /^b/i self =~ /^(true|yes)$/ ? true : false else to_s end else case self when /(^\[.*?\]$| *, *)/ gsub(/^\[ *| *\]$/, '').split(/ *, */) when /^[0-9]+$/ to_i when /^[0-9]+\.[0-9]+$/ to_f when /^:\w+/ sub(/^:/, '').to_sym when /^(true|yes)$/i true when /^(false|no)$/i false else to_s end end end |
#simple_wrap(width) ⇒ Object
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
# File 'lib/doing/string.rb', line 213 def simple_wrap(width) str = gsub(/@\S+\(.*?\)/) { |tag| tag.gsub(/\s/, '%%%%') } words = str.split(/ /).map { |word| word.gsub(/%%%%/, ' ') } out = [] line = [] words.each do |word| if word.uncolor.length >= width chars = word.uncolor.split('') out << chars.slice!(0, width - 1).join('') while chars.count >= width line << chars.join('') next elsif line.join(' ').uncolor.length + word.uncolor.length + 1 > width out.push(line.join(' ')) line.clear end line << word.uncolor end out.push(line.join(' ')) out.join("\n") end |
#split_date_range ⇒ Array<DateTime>
Splits a range string and returns an array of DateTime objects as [start, end]. If only one date is given, end time is nil.
"mon 3pm to mon 5pm".split_date_range
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
# File 'lib/doing/string_chronify.rb', line 178 def split_date_range time_rx = /^(\d{1,2}+(:\d{1,2}+)?( *(am|pm))?|midnight|noon)$/ range_rx = / (to|through|thru|(?:un)?til|-+) / date_string = dup if date_string.is_range? # Do we want to differentiate between "to" and "through"? # inclusive = date_string =~ / (through|thru|-+) / ? true : false inclusive = true dates = date_string.split(range_rx) if dates[0].strip =~ time_rx && dates[-1].strip =~ time_rx start = dates[0].strip finish = dates[-1].strip else start = dates[0].chronify(guess: :begin, future: false) finish = dates[-1].chronify(guess: inclusive ? :end : :begin, future: false) end raise Errors::InvalidTimeExpression, 'Unrecognized date string' if start.nil? || finish.nil? else if date_string.strip =~ time_rx start = date_string.strip finish = nil else start = date_string.strip.chronify(guess: :begin, future: false) finish = date_string.strip.chronify(guess: :end) end raise Errors::InvalidTimeExpression, 'Unrecognized date string' unless start end if start.is_a? String Doing.logger.debug('Parser:', "--from string interpreted as time span, from #{start || '12am'} to #{finish || '11:59pm'}") else Doing.logger.debug('Parser:', "date range interpreted as #{start.strftime('%F %R')} -- #{finish ? finish.strftime('%F %R') : 'now'}") end [start, finish] end |
#tag(tag, value: nil, remove: false, rename_to: nil, regex: false, single: false, force: false) ⇒ String
Add, rename, or remove a tag
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 |
# File 'lib/doing/string.rb', line 526 def tag(tag, value: nil, remove: false, rename_to: nil, regex: false, single: false, force: false) log_level = single ? :info : :debug title = dup title.chomp! tag = tag.sub(/^@?/, '') case_sensitive = tag !~ /[A-Z]/ rx_tag = if regex tag.gsub(/\./, '\S') else tag.gsub(/\?/, '.').gsub(/\*/, '\S*?') end if remove || rename_to rx = Regexp.new("(?<=^| )@#{rx_tag}(?<parens>\\((?<value>[^)]*)\\))?(?= |$)", case_sensitive) m = title.match(rx) if m.nil? && rename_to && force title.tag!(rename_to, value: value, single: single) elsif m title.gsub!(rx) do rename_to ? "@#{rename_to}#{value.nil? ? m['parens'] : "(#{value})"}" : '' end title. title.chomp! if rename_to f = "@#{tag}".cyan t = "@#{rename_to}".cyan Doing.logger.write(log_level, 'Tag:', %(renamed #{f} to #{t} in "#{title}")) else f = "@#{tag}".cyan Doing.logger.write(log_level, 'Tag:', %(removed #{f} from "#{title}")) end else Doing.logger.debug('Skipped:', "not tagged #{"@#{tag}".cyan}") end elsif title =~ /@#{tag}(?=[ (]|$)/ Doing.logger.debug('Skipped:', "already tagged #{"@#{tag}".cyan}") return title else add = tag add += "(#{value})" unless value.nil? title.chomp! title += " @#{add}" title. title.chomp! Doing.logger.write(log_level, 'Tag:', %(added #{('@' + tag).cyan} to "#{title}")) end title.gsub(/ +/, ' ') end |
#tag!(tag, **options) ⇒ Object
Add, rename, or remove a tag in place
509 510 511 |
# File 'lib/doing/string.rb', line 509 def tag!(tag, **) replace tag(tag, **) end |
#time_string(format: :dhm) ⇒ Object
Convert DD:HH:MM to a natural language string
117 118 119 |
# File 'lib/doing/string_chronify.rb', line 117 def time_string(format: :dhm) to_seconds.time_string(format: format) end |
#to_bool ⇒ Object
697 698 699 700 701 702 703 704 |
# File 'lib/doing/string.rb', line 697 def to_bool case self when /^[yt1]/i true else false end end |
#to_p(number) ⇒ Object
Pluralize a string based on quantity
311 312 313 |
# File 'lib/doing/string.rb', line 311 def to_p(number) number == 1 ? self : "#{self}s" end |
#to_phrase_query(query) ⇒ Object
104 105 106 107 108 109 |
# File 'lib/doing/string.rb', line 104 def to_phrase_query(query) parser = PhraseParser::QueryParser.new transformer = PhraseParser::QueryTransformer.new parse_tree = parser.parse(query) transformer.apply(parse_tree).to_elasticsearch end |
#to_rx(distance: nil, case_type: nil) ⇒ Regexp
Convert string to fuzzy regex. Characters in words can be separated by up to distance characters in haystack, spaces indicate unlimited distance.
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/doing/string.rb', line 31 def to_rx(distance: nil, case_type: nil) distance ||= Doing.config.settings.dig('search', 'distance').to_i || 3 case_type ||= Doing.config.settings.dig('search', 'case')&.normalize_case || :smart case_sensitive = case case_type when :smart self =~ /[A-Z]/ ? true : false when :sensitive true else false end pattern = case dup.strip when %r{^/.*?/$} sub(%r{/(.*?)/}, '\1') when /^'/ sub(/^'(.*?)'?$/, '\1') else split(/ +/).map do |w| w.split('').join(".{0,#{distance}}").gsub(/\+/, '\+').wildcard_to_rx end.join('.*?') end Regexp.new(pattern, !case_sensitive) end |
#to_seconds ⇒ Integer
Convert DD:HH:MM to seconds
101 102 103 104 105 106 107 108 109 110 |
# File 'lib/doing/string_chronify.rb', line 101 def to_seconds mtch = match(/(\d+):(\d+):(\d+)/) raise Errors::DoingRuntimeError, "Invalid time string: #{self}" unless mtch h = mtch[1] m = mtch[2] s = mtch[3] (h.to_i * 60 * 60) + (m.to_i * 60) + s.to_i end |
#to_tags ⇒ Array
Convert a list of tags to an array. Tags can be with or without @ symbols, separated by any character, and can include parenthetical values (with spaces)
480 481 482 |
# File 'lib/doing/string.rb', line 480 def gsub(/ *, */, ' ').scan(/(@?(?:\S+(?:\(.+\)))|@?(?:\S+))/).map(&:first).sort.uniq.map(&:add_at) end |
#truncate(len, ellipsis: '...') ⇒ Object
Truncate to nearest word
162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
# File 'lib/doing/string.rb', line 162 def truncate(len, ellipsis: '...') return self if length <= len total = 0 res = [] split(/ /).each do |word| break if total + 1 + word.length > len total += 1 + word.length res.push(word) end res.join(' ') + ellipsis end |
#truncate!(len, ellipsis: '...') ⇒ Object
177 178 179 |
# File 'lib/doing/string.rb', line 177 def truncate!(len, ellipsis: '...') replace truncate(len, ellipsis: ellipsis) end |
#truncmiddle(len, ellipsis: '...') ⇒ Object
Truncate string in the middle
187 188 189 190 191 192 193 194 |
# File 'lib/doing/string.rb', line 187 def truncmiddle(len, ellipsis: '...') return self if length <= len len -= (ellipsis.length / 2).to_i total = length half = total / 2 cut = (total - len) / 2 sub(/(.{#{half - cut}}).*?(.{#{half - cut}})$/, "\\1#{ellipsis}\\2") end |
#truncmiddle!(len, ellipsis: '...') ⇒ Object
196 197 198 |
# File 'lib/doing/string.rb', line 196 def truncmiddle!(len, ellipsis: '...') replace truncmiddle(len, ellipsis: ellipsis) end |
#truthy? ⇒ Boolean
Test string for truthiness (0, "f", "false", "n", "no" all return false, case insensitive, otherwise true)
61 62 63 64 65 66 67 |
# File 'lib/doing/string.rb', line 61 def truthy? if self =~ /^(0|f(alse)?|n(o)?)$/i false else true end end |
#uncolor ⇒ Object
Remove color escape codes
205 206 207 |
# File 'lib/doing/string.rb', line 205 def uncolor gsub(/\e\[[\d;]+m/,'') end |
#uncolor! ⇒ Object
209 210 211 |
# File 'lib/doing/string.rb', line 209 def uncolor! replace uncolor end |
#validate_color ⇒ String
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Extract the longest valid color from a string.
Allows %colors to bleed into other text and still be recognized, e.g. %greensomething still finds %green.
18 19 20 21 22 23 24 25 26 27 |
# File 'lib/doing/template_string.rb', line 18 def validate_color valid_color = nil compiled = '' split('').each do |char| compiled += char valid_color = compiled if Color.attributes.include?(compiled.to_sym) end valid_color end |
#wildcard_to_rx ⇒ String
Convert ? and * wildcards to regular expressions. Uses \S (non-whitespace) instead of . (any character)
451 452 453 |
# File 'lib/doing/string.rb', line 451 def wildcard_to_rx gsub(/\?/, '\S').gsub(/\*/, '\S*?') end |
#wrap(len, pad: 0, indent: ' ', offset: 0, prefix: '', color: '', after: '', reset: '', pad_first: false) ⇒ Object
Wrap string at word breaks, respecting tags
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
# File 'lib/doing/string.rb', line 243 def wrap(len, pad: 0, indent: ' ', offset: 0, prefix: '', color: '', after: '', reset: '', pad_first: false) last_color = color.empty? ? '' : after.last_color note_rx = /(?mi)(?<!\\)%(?<width>-?\d+)?(?:\^(?<mchar>.))?(?:(?<ichar>[ _t]|[^a-z0-9])(?<icount>\d+))?(?<prefix>.[ _t]?)?note/ note = '' after = after.dup if after.frozen? after.sub!(note_rx) do note = Regexp.last_match(0) '' end left_pad = ' ' * offset left_pad += indent # return "#{left_pad}#{prefix}#{color}#{self}#{last_color} #{note}" unless len.positive? # Don't break inside of tag values str = gsub(/@\S+\(.*?\)/) { |tag| tag.gsub(/\s/, '%%%%') }.gsub(/\n/, ' ') words = str.split(/ /).map { |word| word.gsub(/%%%%/, ' ') } out = [] line = [] words.each do |word| if word.uncolor.length >= len chars = word.uncolor.split('') out << chars.slice!(0, len - 1).join('') while chars.count >= len line << chars.join('') next elsif line.join(' ').uncolor.length + word.uncolor.length + 1 > len out.push(line.join(' ')) line.clear end line << word.uncolor end out.push(line.join(' ')) last_color = '' out[0] = format("%-#{pad}s%s%s", out[0], last_color, after) out.map.with_index { |l, idx| if !pad_first && idx == 0 "#{color}#{prefix}#{l}#{last_color}" else "#{left_pad}#{color}#{prefix}#{l}#{last_color}" end }.join("\n") + " #{note}".chomp # res.join("\n").strip + last_color + " #{note}".chomp end |