Class: Yast::StringClass

Inherits:
Module
  • Object
show all
Includes:
Logger
Defined in:
library/types/src/modules/String.rb

Constant Summary

UPPER_CHARS =
Note:

it is ascii chars only

"ABCDEFGHIJKLMNOPQRSTUVWXYZ".freeze
LOWER_CHARS =
"abcdefghijklmnopqrstuvwxyz".freeze
ALPHA_CHARS =
UPPER_CHARS + LOWER_CHARS
DIGIT_CHARS =
"0123456789".freeze
ALPHA_NUM_CHARS =
ALPHA_CHARS + DIGIT_CHARS
PUNCT_CHARS =
"!\"\#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".freeze
GRAPHICAL_CHARS =
ALPHA_NUM_CHARS + PUNCT_CHARS
SPACE_CHARS =
"\f\r\n\t\v".freeze
PRINTABLE_CHARS =
SPACE_CHARS + GRAPHICAL_CHARS

Instance Method Summary collapse

Instance Method Details

#CAlnumObject

The 62 upper and lowercase ASCII letters and digits



572
573
574
# File 'library/types/src/modules/String.rb', line 572

def CAlnum
  ALPHA_NUM_CHARS
end

#CAlphaObject

The 52 upper and lowercase ASCII letters



562
563
564
# File 'library/types/src/modules/String.rb', line 562

def CAlpha
  ALPHA_CHARS
end

#CDigitObject

Digits: 0123456789



567
568
569
# File 'library/types/src/modules/String.rb', line 567

def CDigit
  DIGIT_CHARS
end

#CGraphObject

Printable ASCII charcters except whitespace, 33-126



577
578
579
# File 'library/types/src/modules/String.rb', line 577

def CGraph
  GRAPHICAL_CHARS
end

#CLowerObject

The 26 lowercase ASCII letters



557
558
559
# File 'library/types/src/modules/String.rb', line 557

def CLower
  LOWER_CHARS
end

#CPrintObject

Printable ASCII characters including whitespace



582
583
584
# File 'library/types/src/modules/String.rb', line 582

def CPrint
  PRINTABLE_CHARS
end

#CutBlanks(input) ⇒ Object

Deprecated.

if remove also n then use String#strip, otherwise simple sub is enough

Remove spaces and tabs at begin and end of input string.

Examples:

CutBlanks(“ tany input ”) -> “any input”

Parameters:

  • input (String)

    string to be stripped

Returns:

  • stripped string



256
257
258
259
260
# File 'library/types/src/modules/String.rb', line 256

def CutBlanks(input)
  return "" if input.nil?

  input.sub(/\A[ \t]*(.*[^ \t])[ \t]*\z/, "\\1")
end

#CutRegexMatch(input, regex, glob) ⇒ String

Remove first or every match of given regular expression from a string

(e.g. CutRegexMatch( “abcdef12ef34gh000”, “[0-9]+”, true ) -> “abcdefefgh”, CutRegexMatch( “abcdef12ef34gh000”, “[0-9]+”, false ) -> “abcdefef34gh000”)

Parameters:

  • input (String)

    string that might occur regex

  • regex (String)

    regular expression to search for, must not contain brackets

  • glob (Boolean)

    flag if only first or every occuring match should be removed

Returns:

  • (String)

    that has matches removed



510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
# File 'library/types/src/modules/String.rb', line 510

def CutRegexMatch(input, regex, glob)
  return "" if input.nil? || input.empty?
  output = input
  if Builtins.regexpmatch(output, regex)
    p = Builtins.regexppos(output, regex)
    loop do
      first_index = p[0]
      lenght = p[1] || 0

      output = output[0, first_index] + output[(first_index + lenght)..-1]
      p = Builtins.regexppos(output, regex)
      break unless glob
      break if p.empty?
    end
  end
  output
end

#CutZeros(input) ⇒ String

Deprecated.

if conversion to integer is needed in decimal use String#to_i

Remove any leading zeros

Remove any leading zeros that make tointeger inadvertently assume an octal number (e.g. “09” -> “9”, “0001” -> “1”, but “0” -> “0”)

Parameters:

  • input (String)

    number that might contain leadig zero

Returns:

  • (String)

    that has leading zeros removed



271
272
273
274
275
# File 'library/types/src/modules/String.rb', line 271

def CutZeros(input)
  return "" if input.nil?

  input.sub(/\A0*([0-9])/, "\\1")
end

#EscapeTags(text) ⇒ String

Function for escaping (replacing) (HTML|XML…) tags with their (HTML|XML…) meaning.

Usable to present text “as is” in RichText.

Parameters:

Returns:



535
536
537
538
539
540
541
542
543
544
# File 'library/types/src/modules/String.rb', line 535

def EscapeTags(text)
  return nil unless text
  text = text.dup

  text.gsub!("&", "&amp;")
  text.gsub!("<", "&lt;")
  text.gsub!(">", "&gt;")

  text
end

#FindMountPoint(dir, dirs) ⇒ Object

Find a mount point for given directory/file path. Returns “/” if no mount point matches

Parameters:

  • dir

    requested path , e.g. “/usr/share”

  • dirs

    list of mount points, e.g. [ “/”, “/usr”, “/boot” ]

Returns:

  • string a mount point from the input list or “/” if not found



774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'library/types/src/modules/String.rb', line 774

def FindMountPoint(dir, dirs)
  dirs = deep_copy(dirs)
  while !dir.nil? && dir != "" && !Builtins.contains(dirs, dir)
    # strip the last path component and try it again
    comps = Builtins.splitstring(dir, "/")
    comps = Builtins.remove(comps, Ops.subtract(Builtins.size(comps), 1))
    dir = Builtins.mergestring(comps, "/")
  end

  dir = "/" if dir.nil? || dir == ""

  dir
end

#FirstChunk(s, separators) ⇒ Object

Shorthand for select (splitstring (s, separators), 0, “”) Useful now that the above produces a deprecation warning.

Parameters:

  • s (String)

    string to be split

  • separators (String)

    characters which delimit components

Returns:

  • first component or “”



551
552
553
554
# File 'library/types/src/modules/String.rb', line 551

def FirstChunk(s, separators)
  return "" if !s || !separators
  s[/\A[^#{separators}]*/]
end

#FormatFilename(file_path, len) ⇒ String

Format file name - truncate the middle part of the directory to fit to the reqested lenght. Path elements in the middle of the string are replaced by ellipsis (…). The result migth be longer that requested size if size of the last element (with ellipsis) is longer than the requested size. If the requested size is greater than size of the input then the string is not modified. The last part (file name) is never removed.

Examples:

FormatFilename(“/really/very/long/file/name”, 15) -> “/…/file/name”

FormatFilename(“/really/very/long/file/name”, 5) -> “…/name”

FormatFilename(“/really/very/long/file/name”, 100) -> “/really/very/long/file/name”

Parameters:

  • file_path (String)

    file name

  • len (Fixnum)

    requested maximum lenght of the output

Returns:

  • (String)

    Truncated file name



711
712
713
714
715
716
717
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
# File 'library/types/src/modules/String.rb', line 711

def FormatFilename(file_path, len)
  return nil unless file_path
  return file_path if len && len > file_path.size

  dir = file_path.split("/", -1)
  file = dir.pop

  # there is a slash at the end, add the directory name
  file = dir.pop + "/" if file == ""

  if dir.join("/").size <= 3
    # the path is short, replacing by ... cannot help
    return file_path
  end

  ret = ""
  loop do
    # ellipsis - used to replace part of text to make it shorter
    # example: "/really/very/long/file/name", "/.../file/name")
    ellipsis = _("...")
    dir[dir.size / 2] = ellipsis

    ret = (dir + [file]).join("/")

    break unless len # funny backward compatibility that for nil len remove one element

    # the size is OK
    break if ret.size <= len

    # still too long, remove the ellipsis and start a new iteration
    dir.delete(ellipsis)

    break if dir.empty?
  end

  ret
end

#FormatRateMessage(text, avg_bps, curr_bps) ⇒ String

Add a download rate status to a message.

Add the current and the average download rate to the message.

Parameters:

  • text (String)

    the message with %1 placeholder for the download rate string

  • avg_bps (Fixnum)

    average download rate (in B/s)

  • curr_bps (Fixnum)

    current download rate (in B/s)

Returns:

  • (String)

    formatted message



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
# File 'library/types/src/modules/String.rb', line 188

def FormatRateMessage(text, avg_bps, curr_bps)
  rate = ""
  curr_bps ||= 0
  avg_bps ||= 0

  if curr_bps > 0
    rate = format_rate(curr_bps)

    if avg_bps > 0
      # format download rate message: %1 = the current download rate (e.g. "242.6kB/s")
      # %2 is the average download rate (e.g. "228.3kB/s")
      # to translators: keep translation of "on average" as short as possible
      rate = Builtins.sformat(
        _("%1 (on average %2)"),
        rate,
        format_rate(avg_bps)
      )
    end
  end

  # add download rate to the downloading message
  # %1 is URL, %2 is formatted download rate, e.g. "242.6kB/s (avg. 228.3kB/s)"
  # in ncurses UI the strings are exchanged (%1 is the rate, %2 is URL)
  # due to limited space on the screen
  Builtins.sformat(text, rate)
end

#FormatSize(bytes) ⇒ Object

Return a pretty description of a byte count

Return a pretty description of a byte count, with two fraction digits and using B, KiB, MiB, GiB or TiB as unit as appropriate.

Uses the current locale defined decimal separator (i.e. the result is language dependant).

Examples:

FormatSize(23456767890) -> “223.70 MiB”

Parameters:

  • bytes (Fixnum)

    size (e.g. free diskspace) in Bytes

Returns:

  • formatted string



172
173
174
175
176
177
# File 'library/types/src/modules/String.rb', line 172

def FormatSize(bytes)
  return "" unless bytes

  # automatic precision, don't print trailing zeroes for sizes < 1MiB
  FormatSizeWithPrecision(bytes, -1, Ops.less_than(bytes, 1 << 20))
end

#FormatSizeWithPrecision(bytes, precision, omit_zeroes) ⇒ Object

Return a pretty description of a byte count

Return a pretty description of a byte count with required precision and using B, KiB, MiB, GiB or TiB as unit as appropriate.

Uses the current locale defined decimal separator (i.e. the result is language dependant).

(useful for memory size - 128 MiB RAM looks better than 128.00 MiB RAM)

Examples:

FormatSizeWithPrecision(128, 2, true) -> “128 B”

FormatSizeWithPrecision(4096, 2, true) -> “4 KiB”

FormatSizeWithPrecision(4096, 2, false) -> “4.00 KiB”

FormatSizeWithPrecision(1024*1024, 2, true) -> “1 MiB”

Parameters:

  • bytes (Fixnum)

    size (e.g. free diskspace, memory size) in Bytes

  • precision (Fixnum)

    number of fraction digits in output, if negative (less than 0) the precision is set automatically depending on the suffix

  • omit_zeroes (Boolean)

    if true then do not add zeroes

Returns:

  • formatted string



122
123
124
125
126
127
128
129
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
# File 'library/types/src/modules/String.rb', line 122

def FormatSizeWithPrecision(bytes, precision, omit_zeroes)
  return "" if bytes.nil?

  units = [
    # Byte abbreviated
    _("B"),
    # KiloByte abbreviated
    _("KiB"),
    # MegaByte abbreviated
    _("MiB"),
    # GigaByte abbreviated
    _("GiB"),
    # TeraByte abbreviated
    _("TiB")
  ]

  index = 0
  whole = bytes.to_f

  while (whole >= 1024.0 || whole <= -1024.0) && (index + 1) < units.size
    whole /= 1024.0
    index += 1
  end

  precision ||= 0
  # auto precision - depends on the suffix, but max. 3 decimal digits
  precision = index < 3 ? index : 3 if precision < 0

  if omit_zeroes == true
    max_difference = 0.9
    max_difference /= (10.0 * precision)

    precision = 0 if (whole - whole.round).abs < max_difference
  end

  Builtins::Float.tolstring(whole, precision) + " " + units[index]
end

#FormatTime(seconds) ⇒ String

Format an integer seconds value with min:sec or hours:min:sec

Parameters:

  • seconds (Fixnum)

    time (in seconds)

Returns:

  • (String)

    formatted string (empty for negative values)



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'library/types/src/modules/String.rb', line 229

def FormatTime(seconds)
  return "nil:nil:nil" unless seconds # funny backward compatibility
  return "" if seconds < 0

  if seconds < 3600 # Less than one hour
    return Builtins.sformat(
      "%1:%2",
      FormatTwoDigits(seconds / 60),
      FormatTwoDigits(seconds % 60)
    ) # More than one hour - we don't hope this will ever happen, but who knows?
  else
    hours = seconds / 3600
    seconds = seconds % 3600
    return Builtins.sformat(
      "%1:%2:%3",
      hours,
      FormatTwoDigits(seconds / 60),
      FormatTwoDigits(seconds % 60)
    )
  end
end

#FormatTwoDigits(x) ⇒ String

Format an integer number as (at least) two digits; use leading zeroes if necessary.

Parameters:

  • x (Fixnum)

    input

Returns:

  • (String)

    number as two-digit string



220
221
222
223
# File 'library/types/src/modules/String.rb', line 220

def FormatTwoDigits(x)
  msg = (0..9).member?(x) ? "0%1" : "%1"
  Builtins.sformat(msg, x)
end

#mainObject



47
48
49
# File 'library/types/src/modules/String.rb', line 47

def main
  textdomain "base"
end

#NewlineItems(s) ⇒ Object

Returns the items as a list, with empty lines removed

Parameters:

  • s (String)

    n-terminated items

Returns:

  • the items as a list, with empty lines removed



91
92
93
94
95
# File 'library/types/src/modules/String.rb', line 91

def NewlineItems(s)
  return nil unless s

  NonEmpty(s.split("\n"))
end

#NonEmpty(l) ⇒ Object

Returns only non-“” items

Parameters:

  • l (Array<String>)

    a list of strings

Returns:

  • only non-“” items



84
85
86
87
# File 'library/types/src/modules/String.rb', line 84

def NonEmpty(l)
  return nil unless l
  l.reject { |i| i == "" }
end

#OptParens(s) ⇒ Object

Optional parenthesized text



78
79
80
# File 'library/types/src/modules/String.rb', line 78

def OptParens(s)
  opt_format(" (%1)", s)
end

#Pad(text, length) ⇒ Object

Add spaces after the text to make it long enough

Add spaces after the text to make it long enough. If the text is longer than requested, no changes are made.

Parameters:

  • text (String)

    text to be padded

  • length (Fixnum)

    requested length

Returns:

  • padded text



318
319
320
# File 'library/types/src/modules/String.rb', line 318

def Pad(text, length)
  SuperPad(text, length, " ", :left)
end

#PadZeros(text, length) ⇒ Object

Add zeros before the text to make it long enough.

Add zeros before the text to make it long enough. If the text is longer than requested, no changes are made.

Parameters:

  • text (String)

    text to be padded

  • length (Fixnum)

    requested length

Returns:

  • padded text



330
331
332
# File 'library/types/src/modules/String.rb', line 330

def PadZeros(text, length)
  SuperPad(text, length, "0", :right)
end

#ParseOptions(options, parameters) ⇒ Array<String>

Parse string of values

Parse string of values - split string to values, quoting and backslash sequences are supported “separator”:<string> - value separator (default: “ t”), “unique”:<boolean> - result will not contain any duplicates, first occurance of the string is stored into output (default: false), “interpret_backslash”:<boolean> - convert backslash sequence into one character (e.g. “\n” => “n”) (default: true) “remove_whitespace”:<boolean> - remove white spaces around values (default: true),

Parameters:

  • options (String)

    Input string

  • parameters (Hash)

    Parmeter used at parsing - map with keys:

Returns:

  • (Array<String>)

    List of strings



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'library/types/src/modules/String.rb', line 344

def ParseOptions(options, parameters)
  parameters ||= {}
  ret = []

  # parsing options
  separator = parameters["separator"] || " \t"
  unique = parameters.fetch("unique", false)
  interpret_backslash = parameters.fetch("interpret_backslash", true)
  remove_whitespace = parameters.fetch("remove_whitespace", true)

  log.debug "Input: string: '#{options}', parameters: #{parameters}"

  return [] unless options

  # two algorithms are used:
  # first is much faster, but only usable if string
  # doesn't contain any double qoute characters
  # and backslash sequences are not interpreted
  # second is more general, but of course slower

  if options.include?("\"") && !interpret_backslash
    # easy case - no qouting, don't interpres backslash sequences => use splitstring
    values = options.split(/[#{separator}]/)

    values.each do |v|
      v = CutBlanks(v) if remove_whitespace == true
      ret << v if !unique || !ret.include?(v)
    end
  else
    # quoting is used or backslash interpretation is enabled
    # so it' not possible to split input
    # parsing each character is needed - use finite automaton

    # state
    state = :out_of_string
    # position in the input string
    index = 0
    # parsed value - buffer
    str = ""

    while index < options.size
      character = options[index]

      log.debug "character: #{character} state: #{state} index: #{index}"

      # interpret backslash sequence
      if character == "\\" && interpret_backslash
        nextcharacter = options[index + 1]
        if nextcharacter
          index += 1

          # backslah sequences
          backslash_seq = {
            "a"  => "\a", # alert
            "b"  => "\b", # backspace
            "e"  => "\e", # escape
            "f"  => "\f", # FF
            "n"  => "\n", # NL
            "r"  => "\r", # CR
            "t"  => "\t", # tab
            "v"  => "\v", # vertical tab
            "\\" => "\\", # backslash
            # backslash will be removed later,
            # double quote and escaped double quote have to be different
            # as it have different meaning
            "\"" => "\\\""
          }

          character = if backslash_seq[nextcharacter]
            backslash_seq[nextcharacter]
          else
            # ignore backslash in invalid backslash sequence
            nextcharacter
          end

          log.debug "backslash sequence: '#{character}'"
        else
          log.warn "Missing character after backslash (\\) at the end of string"
        end
      end

      if state == :out_of_string
        # ignore separator or white space at the beginning of the string
        if separator.include?(character) || remove_whitespace && character =~ /[ \t]/
          index += 1
          next
        # start of a quoted string
        elsif character == "\""
          state = :in_quoted_string
        else
          # start of a string
          state = :in_string

          str = (character == "\\\"") ? "\"" : character
        end
      # after double quoted string - handle non-separator chars after double quote
      elsif state == :in_quoted_string_after_dblqt
        if separator.include?(character)
          ret << str if !unique || !Builtins.contains(ret, str)

          str = ""
          state = :out_of_string
        elsif character == "\\\""
          str << "\""
        else
          str << character
        end
      elsif state == :in_quoted_string
        if character == "\""
          # end of quoted string
          state = :in_quoted_string_after_dblqt
        elsif character == "\\\""
          str << "\""
        else
          str << character
        end
      elsif state == :in_string
        if separator.include?(character)
          state = :out_of_string

          str = CutBlanks(str) if remove_whitespace

          ret << str if !unique || !ret.include?(str)

          str = ""
        elsif character == "\\\""
          str << "\""
        else
          str << character
        end
      end

      index += 1
    end

    # error - still in quoted string
    if state == :in_quoted_string || state == :in_quoted_string_after_dblqt
      if state == :in_quoted_string
        log.warn "Missing trainling double quote character(\") in input: '#{options}'"
      end

      ret << str if !unique || !ret.include?(str)
    end

    # process last string in the buffer
    if state == :in_string
      str = CutBlanks(str) if remove_whitespace

      ret << str if !unique || !ret.include?(str)
    end
  end

  log.debug "Parsed values: #{ret}"

  ret
end

#Quote(var) ⇒ Object

Quote a string with 's

More precisely it protects single quotes inside the string but does not prepend or append single quotes.

Examples:

quote(“a'b”) -> “a'''b”

Parameters:

  • var (String)

    unquoted string

Returns:

  • quoted string



59
60
61
62
63
# File 'library/types/src/modules/String.rb', line 59

def Quote(var)
  return "" if var.nil?

  var.gsub("'", "'\\\\''")
end

#Random(len) ⇒ Object

Make a random base-36 number. srandom should be called beforehand.

Parameters:

  • len (Fixnum)

    string length

Returns:

  • random string of 0-9 and a-z



690
691
692
693
694
695
696
# File 'library/types/src/modules/String.rb', line 690

def Random(len)
  return "" if !len || len <= 0
  digits = DIGIT_CHARS + LOWER_CHARS # uses the character classes from above
  ret = Array.new(len) { digits[rand(digits.size)] }

  ret.join("")
end

#RemoveShortcut(label) ⇒ String

Remove a shortcut from a label, so that it can be inserted into help to avoid risk of different translation of the label

Parameters:

  • label (String)

    string a label possibly including a shortcut

Returns:

  • (String)

    the label without the shortcut mark



753
754
755
756
757
758
759
760
761
762
763
# File 'library/types/src/modules/String.rb', line 753

def RemoveShortcut(label)
  ret = label
  if Builtins.regexpmatch(label, "^(.*[^&])?(&&)*&[[:alnum:]].*$")
    ret = Builtins.regexpsub(
      label,
      "^((.*[^&])?(&&)*)&([[:alnum:]].*)$",
      "\\1\\4"
    )
  end
  ret
end

#Repeat(text, number) ⇒ String

Deprecated.

use String#operator* instead

Repeat a string

Repeat a string number of times.

Parameters:

  • input

    string to repeat

  • input

    number number of repetitions

Returns:

  • (String)

    repeated string



285
286
287
288
289
# File 'library/types/src/modules/String.rb', line 285

def Repeat(text, number)
  return "" if text.nil? || number.nil? || number < 1

  text * number
end

#Replace(s, source, target) ⇒ String

Replace substring in a string. All substrings source are replaced by string target.

Parameters:

  • s (String)

    input string

  • source (String)

    the string which will be replaced

  • target (String)

    the new string which is used instead of source

Returns:



655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
# File 'library/types/src/modules/String.rb', line 655

def Replace(s, source, target)
  return nil if s.nil?

  if source.nil? || source == ""
    Builtins.y2warning("invalid parameter source: %1", source)
    return s
  end

  if target.nil?
    Builtins.y2warning("invalid parameter target: %1", target)
    return s
  end

  # avoid infinite loop even if it break backward compatibility
  if target.include?(source)
    raise "Target #{target} include #{source} which will lead to infinite loop"
  end

  pos = s.index(source)
  while pos
    tmp = s[0, pos] + target
    tmp << s[(pos + source.size)..-1] if s.size > (pos + source.size)

    s = tmp

    pos = s.index(source)
  end

  s
end

#StartsWith(str, test) ⇒ Object

Checks whether string str starts with test.



766
767
768
# File 'library/types/src/modules/String.rb', line 766

def StartsWith(str, test)
  Builtins.search(str, test) == 0
end

#SuperPad(text, length, padding, alignment) ⇒ Object

Add the padding character around the text to make it long enough

Add the padding character around the text to make it long enough. If the text is longer than requested, no changes are made.

Parameters:

  • text (String)

    text to be padded

  • length (Fixnum)

    requested length

  • padding (String)

    padding character

  • alignment (Symbol)

    alignment to use, either `left or `right

Returns:

  • padded text



301
302
303
304
305
306
307
308
# File 'library/types/src/modules/String.rb', line 301

def SuperPad(text, length, padding, alignment)
  text ||= ""
  return text if length.nil? || text.size >= length || padding.nil?

  pad = padding * (length - text.size)

  alignment == :right ? (pad + text) : (text + pad)
end

#TextTable(header, items, options) ⇒ String

Function creates text table without using HTML tags. (Useful for commandline) Undefined option uses the default one.

Header: [ “Id”, “Configuration”, “Device” ] Items: [ [ “1”, “aaa”, “Samsung Calex” ], [ “2”, “bbb”, “Trivial Trinitron” ] ] Possible Options: horizontal_padding (for columns), table_left_padding (for table)

Parameters:

Returns:



606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
# File 'library/types/src/modules/String.rb', line 606

def TextTable(header, items, options)
  options ||= {}
  items ||= []
  current_horizontal_padding = options["horizontal_padding"] || 2
  current_table_left_padding = options["table_left_padding"] || 4

  cols_lenghts = find_longest_records(Builtins.add(items, header))

  # whole table is left-padded
  table_left_padding = Pad("", current_table_left_padding)
  # the last row has no newline
  rows_count = items.size
  table = ""

  table << table_left_padding
  table << table_row(header, cols_lenghts, current_horizontal_padding)
  table << "\n"

  table << table_left_padding
  table << table_header_underline(cols_lenghts, current_horizontal_padding)
  table << "\n"

  items.each_with_index do |row, rows_counter|
    table << table_left_padding
    table << table_row(row, cols_lenghts, current_horizontal_padding)
    table << "\n" if (rows_counter + 1) < rows_count
  end
  table
end

#UnderlinedHeader(header_line, left_padding) ⇒ String

Function returns underlined text header without using HTML tags. (Useful for commandline)

Parameters:

  • string

    header line

  • integer

    left padding

Returns:

  • (String)

    underlined header line



642
643
644
645
646
647
648
# File 'library/types/src/modules/String.rb', line 642

def UnderlinedHeader(header_line, left_padding)
  return nil unless header_line
  left_padding ||= 0

  Pad("", left_padding) + header_line + "\n" +
    Pad("", left_padding) + underline(header_line.size)
end

#UnQuote(var) ⇒ Object

Unquote a string with 's (quoted with quote)

Parameters:

  • var (String)

    quoted string

Returns:

  • unquoted string

See Also:

  • #quote


69
70
71
72
73
74
# File 'library/types/src/modules/String.rb', line 69

def UnQuote(var)
  return "" if var.nil?
  log.debug "var=#{var}"

  var.gsub("'\\''", "'")
end

#ValidCharsFilenameString

Characters valid in a filename (not pathname). Naturally “/” is disallowed. Otherwise, the graphical ASCII characters are allowed.

Returns:



590
591
592
# File 'library/types/src/modules/String.rb', line 590

def ValidCharsFilename
  GRAPHICAL_CHARS.delete("/")
end

#YesNo(value) ⇒ Boolean

Returns value as “Yes” or “No”

Parameters:

  • value (Boolean)

    boolean

Returns:

  • (Boolean)

    value as “Yes” or “No”



99
100
101
102
# File 'library/types/src/modules/String.rb', line 99

def YesNo(value)
  # TRANSLATORS: human text for Boolean value
  value ? _("Yes") : _("No")
end