Class: String

Inherits:
Object
  • Object
show all
Includes:
Doing::Color
Defined in:
lib/doing/string.rb

Overview

String helpers

Constant Summary

Constants included from Doing::Color

Doing::Color::ATTRIBUTES, Doing::Color::ATTRIBUTE_NAMES, Doing::Color::COLORED_REGEXP

Instance Method Summary collapse

Methods included from Doing::Color

attributes, coloring=, coloring?, #support?

Instance Method Details

#add_tags(tags, remove: false) ⇒ Object



280
281
282
283
284
285
# File 'lib/doing/string.rb', line 280

def add_tags(tags, remove: false)
  title = self.dup
  tags = tags.to_tags
  tags.each { |tag| title.tag!(tag, remove: remove) }
  title
end

#add_tags!(tags, remove: false) ⇒ Object



276
277
278
# File 'lib/doing/string.rb', line 276

def add_tags!(tags, remove: false)
  replace add_tags(tags, remove: remove)
end

#cap_first ⇒ Object

Capitalize on the first character on string

Returns:

  • Capitalized string



194
195
196
197
198
# File 'lib/doing/string.rb', line 194

def cap_first
  sub(/^\w/) do |m|
    m.upcase
  end
end

#dedup_tags ⇒ Object



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/doing/string.rb', line 354

def dedup_tags
  title = dup
  tags = title.scan(/(?<=\A| )(@(\S+?)(\([^)]+\))?)(?= |\Z)/).uniq
  tags.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

Remove duplicate tags, leaving only first occurrence

Returns:

  • Deduplicated string



350
351
352
# File 'lib/doing/string.rb', line 350

def dedup_tags!
  replace dedup_tags
end

#highlight_tags(color = 'yellow') ⇒ String

Colorize @tags with ANSI escapes

Parameters:

  • color (String) (defaults to: 'yellow') —

    color (see #Color)

Returns:

  • (String) —

    string with @tags highlighted



78
79
80
81
82
83
84
85
86
87
# File 'lib/doing/string.rb', line 78

def highlight_tags(color = 'yellow')
  escapes = scan(/(\e\[[\d;]+m)[^\e]+@/)
  tag_color = Doing::Color.send(color)
  last_color = if !escapes.empty?
                 escapes[-1][0]
               else
                 Doing::Color.default
               end
  gsub(/(\s|m)(@[^ ("']+)/, "\\1#{tag_color}\\2#{last_color}")
end

#highlight_tags!(color = 'yellow') ⇒ Object

Parameters:

  • color (String) (defaults to: 'yellow') —

    color (see #Color)



67
68
69
# File 'lib/doing/string.rb', line 67

def highlight_tags!(color = 'yellow')
  replace highlight_tags(color)
end

#ignore? ⇒ Boolean

Test if line should be ignored

Returns:

  • (Boolean) —

    line is empty or comment



94
95
96
97
# File 'lib/doing/string.rb', line 94

def ignore?
  line = self
  line =~ /^#/ || line =~ /^\s*$/
end

#is_rx? ⇒ Boolean

Determines if receiver is surrounded by slashes or starts with single quote

Returns:

  • (Boolean) —

    True if regex, False otherwise.



14
15
16
# File 'lib/doing/string.rb', line 14

def is_rx?
  self =~ %r{(^/.*?/$|^')}
end


380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/doing/string.rb', line 380

def link_urls(opt = {})
  opt[:format] ||= :html
  str = self.dup

  if :format == :markdown
    # Remove <self-linked> formatting
    str.gsub!(/<(.*?)>/) do |match|
      m = Regexp.last_match
      if m[1] =~ /^https?:/
        m[1]
      else
        match
      end
    end
  end

  # Replace qualified urls
  str.gsub!(%r{(?mi)(?<!["'\[(\\])((http|https)://)([\w\-_]+(\.[\w\-_]+)+)([\w\-.,@?^=%&amp;:/~+#]*[\w\-@^=%&amp;/~+#])?}) do |_match|
    m = Regexp.last_match
    proto = m[1].nil? ? 'http://' : ''
    case opt[:format]
    when :html
      %(<a href="#{proto}#{m[0]}" title="Link to #{m[0].sub(/^https?:\/\//, '')}">[#{m[3]}]</a>)
    when :markdown
      "[#{m[0]}](#{proto}#{m[0]})"
    else
      m[0]
    end
  end

  # Clean up unlinked <urls>
  str.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

  str
end

Turn raw urls into HTML links

Parameters:

  • opt (Hash) (defaults to: {}) —

    Additional Options



376
377
378
# File 'lib/doing/string.rb', line 376

def link_urls!(opt = {})
  replace link_urls(opt)
end

#normalize_bool(default = :and) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/doing/string.rb', line 251

def normalize_bool(default = :and)
  case self
  when /(and|all)/i
    :and
  when /(any|or)/i
    :or
  when /(not|none)/i
    :not
  else
    default.is_a?(Symbol) ? default : default.normalize_bool
  end
end

#normalize_bool!(default = :and) ⇒ Object

Convert a boolean string to a symbol

Returns:

  • Symbol :and, :or, or :not



247
248
249
# File 'lib/doing/string.rb', line 247

def normalize_bool!(default = :and)
  replace normalize_bool(default)
end

#normalize_case(default = :smart) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/doing/string.rb', line 229

def normalize_case(default = :smart)
  case self
  when /^c/i
    :sensitive
  when /^i/i
    :ignore
  when /^s/i
    :smart
  else
    default.is_a?(Symbol) ? default : default.normalize_case
  end
end

#normalize_case! ⇒ Object

Convert a case sensitivity string to a symbol

Returns:

  • Symbol :smart, :sensitive, :ignore



225
226
227
# File 'lib/doing/string.rb', line 225

def normalize_case!
  replace normalize_case
end

#normalize_order(default = 'asc') ⇒ Object



209
210
211
212
213
214
215
216
217
218
# File 'lib/doing/string.rb', line 209

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

Returns:

  • (String) —

    'asc' or 'desc'



205
206
207
# File 'lib/doing/string.rb', line 205

def normalize_order!(default = 'asc')
  replace normalize_order(default)
end

#normalize_trigger ⇒ Object



268
269
270
# File 'lib/doing/string.rb', line 268

def normalize_trigger
  gsub(/\((?!\?:)/, '(?:').downcase
end

#normalize_trigger! ⇒ Object



264
265
266
# File 'lib/doing/string.rb', line 264

def normalize_trigger!
  replace normalize_trigger
end

#tag(tag, value: nil, remove: false, rename_to: nil, regex: false, single: false) ⇒ Object



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/doing/string.rb', line 291

def tag(tag, value: nil, remove: false, rename_to: nil, regex: false, single: 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
    return title unless title =~ /#{rx_tag}(?=[ (]|$)/

    rx = Regexp.new("(^| )@#{rx_tag}(\\([^)]*\\))?(?= |$)", case_sensitive)
    if title =~ rx
      title.gsub!(rx) do
        m = Regexp.last_match
        rename_to ? "#{m[1]}@#{rename_to}#{m[2]}" : m[1]
      end

      title.dedup_tags!
      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.dedup_tags!
    title.chomp!
    Doing.logger.write(log_level, 'Tag:', %(added #{('@' + tag).cyan} to "#{title}"))
  end

  title.gsub(/ +/, ' ')
end

#tag!(tag, value: nil, remove: false, rename_to: nil, regex: false, single: false) ⇒ Object



287
288
289
# File 'lib/doing/string.rb', line 287

def tag!(tag, value: nil, remove: false, rename_to: nil, regex: false, single: false)
  replace tag(tag, value: value, remove: remove, rename_to: rename_to, regex: regex, single: single)
end

#to_rx(distance: 3, case_type: :smart) ⇒ Regexp

Convert string to fuzzy regex. Characters in words can be separated by up to distance characters in haystack, spaces indicate unlimited distance.

/t.0,3h.0,3i.0,3s.0,3.*?w.0,3o.0,3r.0,3d/

Examples:

"this word".to_rx(2) =>

Parameters:

  • distance (Integer) (defaults to: 3) —

    Allowed distance between characters

  • case_type (defaults to: :smart) —

    The case type

Returns:

  • (Regexp) —

    Regex pattern



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/doing/string.rb', line 32

def to_rx(distance: 3, case_type: :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 { |w| w.split('').join(".{0,#{distance}}") }.join('.*?')
            end
  Regexp.new(pattern, !case_sensitive)
end

#to_tags ⇒ Object



272
273
274
# File 'lib/doing/string.rb', line 272

def to_tags
  gsub(/ *, */, ' ').gsub(/ +/, ' ').split(/ /).sort.uniq.map { |t| t.strip.sub(/^@/, '') }
end

#truncate(len, ellipsis: '...') ⇒ Object

Truncate to nearest word

Parameters:

  • len —

    The length



104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/doing/string.rb', line 104

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



119
120
121
# File 'lib/doing/string.rb', line 119

def truncate!(len, ellipsis: '...')
  replace truncate(len, ellipsis: ellipsis)
end

#truncmiddle(len, ellipsis: '...') ⇒ Object

Truncate string in the middle

Parameters:

  • len —

    The length

  • ellipsis (defaults to: '...') —

    The ellipsis



129
130
131
132
133
134
135
136
# File 'lib/doing/string.rb', line 129

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



138
139
140
# File 'lib/doing/string.rb', line 138

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)

Returns:

  • (Boolean) —

    String is truthy



58
59
60
61
62
63
64
# File 'lib/doing/string.rb', line 58

def truthy?
  if self =~ /^(0|f(alse)?|n(o)?)$/i
    false
  else
    true
  end
end

#uncolor ⇒ Object

Remove color escape codes

Returns:

  • clean string



147
148
149
# File 'lib/doing/string.rb', line 147

def uncolor
  gsub(/\e\[[\d;]+m/,'')
end

#uncolor! ⇒ Object



151
152
153
# File 'lib/doing/string.rb', line 151

def uncolor!
  replace uncolor
end

#wrap(len, pad: 0, indent: ' ', offset: 0, prefix: '', after: '', reset: '') ⇒ Object

Wrap string at word breaks, respecting tags

Parameters:

  • len (Integer) —

    The length

  • offset (Integer) (defaults to: 0) —

    (Optional) The width to pad each subsequent line

  • prefix (String) (defaults to: '') —

    (Optional) A prefix to add to each line



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/doing/string.rb', line 162

def wrap(len, pad: 0, indent: '  ', offset: 0, prefix: '', after: '', reset: '')
  note_rx = /(?i-m)(%(?:[io]d|(?:\^[\s\S])?(?:(?:[ _t]|[^a-z0-9])?\d+)?(?:[\s\S][ _t]?)?)?note)/
  str = gsub(/@\w+\(.*?\)/) { |tag| tag.gsub(/\s/, '%%%%') }
  words = str.split(/ /).map { |word| word.gsub(/%%%%/, ' ') }
  out = []
  line = []
  words.each do |word|
    if line.join(' ').length + word.length + 1 > len
      out.push(line.join(' '))
      line.clear
    end

    line << word
  end
  out.push(line.join(' '))
  note = ''
  after.sub!(note_rx) do
    note = Regexp.last_match(0)
    ''
  end

  out[0] = format("%-#{pad}s%s", out[0], after)
  left_pad = ' ' * (offset)
  left_pad += indent
  out.map { |l| "#{left_pad}#{prefix}#{l}" }.join("\n").strip + " #{note}".chomp
end