Class: PlainText::Part

Inherits:
Array
  • Object
show all
Includes:
Util
Defined in:
lib/plain_text/part.rb,
lib/plain_text/part/boundary.rb,
lib/plain_text/part/paragraph.rb

Overview

TODO:

methods

  • flatten

  • SAFE level for command-line tools?

Class to represent a Chapter-like entity like an Array

An instance of this class contains always an even number of elements, either another Part instance or Paragraph-type String-like instance, followed by a Boundary-type String-like instance. The first element is always a former and the last element is always a latter.

Essentially, the instance of this class holds the order information between sub-Part-s (< Array) and/or Paragraph-s (< String) and Boundary-s (< String).

An example instance looks like this:

Part (
  (0) Paragraph::Empty,
  (1) Boundary::General,
  (2) Part::ArticleHeader(
        (0) Paragraph::Title,
        (1) Boundary::Empty
      ),
  (3) Boundary::TitleMain,
  (4) Part::ArticleMain(
        (0) Part::ArticleSection(
              (0) Paragraph::Title,
              (1) Boundary::General,
              (2) Paragraph::General,
              (3) Boundary::General,
              (4) Part::ArticleSubSection(...),
              (5) Boundary::General,
              (6) Paragraph::General,
              (7) Boundary::Empty
            ),
        (1) Boundary::General,
        (2) Paragraph::General,
        (3) Boundary::Empty
      ),
  (5) Boundary::General
)

A Section (Part) always has an even number of elements: pairs of (Part|Paragraph) and Boundary in this order.

Note some standard destructive Array operations, most notably #delete, #delete_if, #reject!, #select!, #filter!, #keep_if, #flatten!, #uniq! may alter the content in a way it breaks the self-inconsistency of the object. Use it at your own risk, if you wish (or don’t).

An instance of this class is always non-equal to that of the standard Array class. To compare it at the Array level, convert a Part class instance into Array with #to_a first and compare them.

For CRUD of elements (contents) of an instance, the following methods are most basic:

  • Create:

    • Insert/Append: #insert to insert. If the specified index is #size}, it means “append”. For primitive operations, specify primitive: true to skip various checks performed to guarantee the self-consistency as an instance of this class.

    • #<< is disabled.

  • Read:

    • Read: #to_a gives the standard Array, and then you can do whatever manipulation allowed for Array. For example, if you delete an element in the returned Array, that does not affect the original Part instance. However, it is a shallow copy, and hence if you alter an element of it destructively (such as String#replace), the original instance, too, is affected.

      • The methods #[] (or its alias #slice) have some restrictions, such as, an odd number of elements cannot be retrieved, so as to conform the returned value is a valid instance of this class.

  • Update:

    • Replace: #[]= has some restrictions, such as, if multiple elements are replaced, they have to be pairs of Paragraph and Boundary. To skip all the checks, do #insert with primitive: true

  • Delete:

    • Delete: #slice! to delete. For primitive operations, specify primitive: true to skip various checks performed to guarantee the self-consistency as an instance of this class.

      • #delete_at is disabled. #delete, #delete_if, #reject!, #select!, #filter!, #keep_if (and #drop_while and #take_whie in recent Ruby) remain enabled, but if you use them, make sure to use them carefully at your own risk, as no self-consistency checks would be performed automatically.

Author:

  • Masa Sakano (Wise Babel Ltd)

Defined Under Namespace

Classes: Boundary, Paragraph

Constant Summary collapse

ERR_MSGS =

Error messages

{
  even_num: 'even number of elements must be specified.',
  use_to_a: 'To handle it as an Array, use to_a first.',
}

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util

even_odd_arrays, positive_array_index, positive_array_index_checked, raise_typeerror

Constructor Details

#initialize(arin, boundaries = nil, recursive: true, compact: true, compacter: true) ⇒ self

Parameters:

  • arin (Array)

    of [Paragraph1, Boundary1, Para2, Bd2, …] or Part/Paragraph if boundaries is given

  • boundaries (Array) (defaults to: nil)

    of Boundary

  • recursive: (Hash) (defaults to: true)

    a customizable set of options

  • compact: (Hash) (defaults to: true)

    a customizable set of options

  • compacter: (Hash) (defaults to: true)

    a customizable set of options



91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/plain_text/part.rb', line 91

def initialize(arin, boundaries=nil, recursive: true, compact: true, compacter: true)
  if !boundaries
    super(arin)
  else

    armain = []
    arin.each_with_index do |ea_e, i|
      armain << ea_e
      armain << (boundaries[i] || Boundary.new(''))
    end
    super armain
  end
  normalize!(recursive: recursive, compact: compact, compacter: compacter)
end

Class Method Details

.parse(inprm, rule: PlainText::ParseRule::RuleConsecutiveLbs) ⇒ PlainText::Part

Parses a given string (or PlainText::Part) and returns this class of instance.

Parameters:

  • inprm (String, Array, Part)
  • rule: (Hash) (defaults to: PlainText::ParseRule::RuleConsecutiveLbs)

    a customizable set of options

Returns:



111
112
113
114
# File 'lib/plain_text/part.rb', line 111

def self.parse(inprm, rule: PlainText::ParseRule::RuleConsecutiveLbs)
  arin = rule.apply(inprm)
  self.new(arin)
end

Instance Method Details

#+(other) ⇒ Object

Plus operator

Parameters:

  • other (Object)

Returns:

  • as self



501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/plain_text/part.rb', line 501

def +(other)
  # ## The following is strict, but a bit redundant.
  # # is_part = true  # Whether "other" is a Part class instance.
  # # %i(to_ary parts boundaries).each do |ea_m|  # %i(...) defined in Ruby 2.0 and later
  # #   is_part &&= other.class.method_defined?(ea_m)
  # # end

  # begin
  #   other_even_odd = 
  #     ([other.parts, other.boundaries] rescue even_odd_arrays(self, size_even: true, filler: ""))
  # rescue NoMethodError
  #   raise TypeError, sprintf("no implicit conversion of %s into %s", other.class.name, self.class.name)
  # end

  # # eg., if self is PlainText::Part::Section, the returned object is the same.
  # ret = self.class.new(self.parts+other_even_odd[0], self.boundaries+other_even_odd[1])
  ret = self.class.new super
  ret.normalize!
end

#-(other) ⇒ Object

Minus operator

Parameters:

  • other (Object)

Returns:

  • as self



526
527
528
529
# File 'lib/plain_text/part.rb', line 526

def -(other)
  ret = self.class.new super
  ret.normalize!
end

#==(other) ⇒ Object

Equal operator

Unless both are kind of Part instances, false is returned. If you want to make comparison in the Array level, do

p1.to_a == a1.to_a

Parameters:

  • other (Object)


479
480
481
482
483
484
485
# File 'lib/plain_text/part.rb', line 479

def ==(other)
  return false if !other.class.method_defined?(:to_ary)
  %i(parts boundaries).each do |ea_m|  # %i(...) defined in Ruby 2.0 and later
    return false if !other.class.method_defined?(ea_m) || (self.public_send(ea_m) != other.public_send(ea_m))  # public_send() defined in Ruby 2.0 (1.9?) and later
  end
  super
end

#[](arg1, *rest) ⇒ Object Also known as: slice

Returns a partial Part-Array (or Object, if a single Integer is specified)

Because the returned object is this class of instance (when a pair of Integer or Range is specified), only an even number of elements, starting from an even number of index, is allowed.

Parameters:

  • arg1 (Integer, Range)
  • arg2 (Hash)

    a customizable set of options

Returns:

  • (Object)

Raises:

  • (RangeError)


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
580
581
582
583
# File 'lib/plain_text/part.rb', line 548

def [](arg1, *rest)
  arg2 = rest[0]
  return super(arg1) if !arg2 && !arg1.class.method_defined?(:exclude_end?)

  check_bracket_args_type_error(arg1, arg2)  # Args are now either (Int, Int) or (Range)

  if arg2
    size2ret = size2extract(arg1, arg2, ignore_error: true)  # maybe nil (if the index is too small).
    raise ArgumentError, ERR_MSGS[:even_num]+" "+ERR_MSGS[:use_to_a] if size2ret.odd?
    begin
      raise ArgumentError, "odd index is not allowed as the starting index for #{self.class.name}.  It must be even. "+ERR_MSGS[:use_to_a] if positive_array_index_checked(arg1, self).odd?
    rescue TypeError, IndexError
      # handled by super
    end
    return super
  end

  begin
    rang = normalize_index_range(arg1)
  rescue IndexError #=> err
    return nil
    # raise RangeError, err.message
  end

  raise RangeError if rang.begin < 0 || rang.end < 0

  # The end is smaller than the begin in the positive index.  Empty instance of this class is returned.
  if rang.end < rang.begin
    return super
  end

  raise RangeError, "odd index is not allowed as the starting Range for #{sefl.class.name}.  It must be even. "+ERR_MSGS[:use_to_a] if rang.begin.odd?
  size2ret = size2extract(rang, skip_renormalize: true)
  raise ArgumentError, ERR_MSGS[:even_num]+" "+ERR_MSGS[:use_to_a] if size2ret.odd?
  super
end

#[]=(arg1, *rest) ⇒ Object

Replaces some of the Array content.

Parameters:

  • arg1 (Integer, Range)
  • arg2 (Hash)

    a customizable set of options

Returns:

  • (Object)

Raises:

  • (RangeError)


591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
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
635
636
# File 'lib/plain_text/part.rb', line 591

def []=(arg1, *rest)
  if rest.size == 1
    arg2, val = [nil, rest[-1]]
  else
    arg2, val = rest
  end

  # Simple substitution to a single element
  return super(arg1, val) if !arg2 && !arg1.class.method_defined?(:exclude_end?)

  check_bracket_args_type_error(arg1, arg2)  # Args are now either (Int, Int) or (Range)

  # raise TypeError, "object to replace must be Array type with an even number of elements." if !val.class.method_defined?(:to_ary) || val.size.odd?

  vals = (val.to_ary rescue [val])
  if arg2
    size2delete = size2extract(arg1, arg2, ignore_error: true)  # maybe nil (if the index is too small).
    raise ArgumentError, "odd-even parity of size of array to replace must be identical to that to slice." if size2delete && ((size2delete % 2) != (vals.size % 2))
    return super
  end

  begin
    rang = normalize_index_range(arg1)
  rescue IndexError => err
    raise RangeError, err.message
  end

  raise RangeError if rang.begin < 0 || rang.end < 0

  # The end is smaller than the begin in the positive index.  It is the same as insert (default in Ruby), except it returns the replaced Object (which may not be an Array).
  if rang.end < rang.begin
    insert(arg1, *vals)
    return val
  end

  size2delete = size2extract(rang, skip_renormalize: true)
  raise ArgumentError, "odd-even parity of size of array to replace must be identical to that to slice." if size2delete && ((size2delete % 2) != (vals.size % 2))
  ret = super

  # The result may not be in an even number anymore.  Correct it.
  Boundary.insert_original_b4_part(size, "") if size.odd?

  # Original method may fill some part of the array with String or even nil.  
  normalize!
  ret
end

#boundariesArray<Boundary>

Returns an array of boundary parts (odd-number-index parts), consisting of Boundaries

Returns:

See Also:



128
129
130
# File 'lib/plain_text/part.rb', line 128

def boundaries
  select.with_index { |_, i| i.odd? } rescue select.each_with_index { |_, i| i.odd? } # Rescue for Ruby 2.1 or earlier
end

#boundary_extended_at(index) ⇒ Array?

returns all the Boundaries immediately before the index and at it as an Array

See #squash_boundary_at! to squash them.

Parameters:

  • index (Integer)

Returns:

  • (Array, nil)

    nil if a too large index is specified.



138
139
140
141
142
143
144
# File 'lib/plain_text/part.rb', line 138

def boundary_extended_at(index)
  (i_pos = get_valid_ipos_for_boundary(index)) || return
  arret = []
  prt = self[i_pos-1]
  arret = prt.public_send(__method__, -1) if prt.class.method_defined? __method__
  arret << self[index]
end

#compact!self, NilClass

Array#compact!

If changed, re-#normalize! it.

Returns:

  • (self, NilClass)


716
717
718
719
# File 'lib/plain_text/part.rb', line 716

def compact!
  ret = super
  ret ? ret.normalize!(recursive: false) : ret
end

#concat(*rest) ⇒ self

Array#concat

Parameters:

Returns:

  • (self)

See Also:



727
728
729
# File 'lib/plain_text/part.rb', line 727

def concat(*rest)
  insert(size, *(rest.sum([])))
end

#deepcopyPart

Returns a dup-ped instance with all the Arrays and Strings dup-ped.

Returns:



149
150
151
# File 'lib/plain_text/part.rb', line 149

def deepcopy
  dup.map!{ |i| i.class.method_defined?(:deepcopy) ? i.deepcopy : i.dup }
end

#each_boundary_with_index(**kwd, &bl) ⇒ Object

each method for boundaries only, providing also the index (always an odd number) to the block.

For just looping over the elements of #boundaries, do simply

boundaries.each do |ec|
end

The indices provided in this method are for the main Array, and hence different from #boundaries.each_with_index

Parameters:

  • recursive: (Hash)

    a customizable set of options

Returns:

  • as self



165
166
167
# File 'lib/plain_text/part.rb', line 165

def each_boundary_with_index(**kwd, &bl)
  map_boundary_core(map: false, with_index: true, **kwd, &bl)
end

#each_part_with_index(**kwd, &bl) ⇒ Object

each method for parts only, providing also the index (always an even number) to the block.

For just looping over the elements of #parts, do simply

parts.each do |ec|
end

The indices provided in this method are for the main Array, and hence different from #parts.each_with_index

Parameters:

  • recursive: (Hash)

    a customizable set of options

Returns:

  • as self



181
182
183
# File 'lib/plain_text/part.rb', line 181

def each_part_with_index(**kwd, &bl)
  map_part_core(map: false, with_index: false, **kwd, &bl)
end

#first_significant_elementInteger?

The first significant (=non-empty) element.

If the returned value is non-nil and destructively altered, self changes.

Returns:

  • (Integer, nil)

    if self.empty? nil is returned.



190
191
192
193
# File 'lib/plain_text/part.rb', line 190

def first_significant_element
  (i = first_significant_index) || return
  self[i]
end

#first_significant_indexInteger?

Index of the first significant (=non-empty) element.

If every element is empty, the last index is returned.

Returns:

  • (Integer, nil)

    if self.empty? nil is returned.



200
201
202
203
204
205
206
# File 'lib/plain_text/part.rb', line 200

def first_significant_index
  return nil if empty?
  each_index do |i|
    return i if self[i] && !self[i].empty?  # self for sanity
  end
  return size-1
end

#index_para?(i, skip_check: false) ⇒ Boolean

True if the index should be semantically for Paragraph?

Parameters:

  • i (Integer)

    index for the array of self

  • skip_check: (Hash) (defaults to: false)

    a customizable set of options

Returns:

  • (Boolean)

See Also:



213
214
215
# File 'lib/plain_text/part.rb', line 213

def index_para?(i, skip_check: false)
  skip_check ? i.even? : positive_array_index_checked(i, self).even?
end

#insert(ind, *rest, primitive: false) ⇒ self

Array#insert

The most basic method to add/insert elements to self. Called from #[]= and #push, for example.

If ind is greater than size, a number of “”, as opposed to nil, are inserted.

Parameters:

  • ind (Index)
  • rest (Array)

    This must have an even number of arguments, unless ind is larger than the array size and an odd number.

  • primitive: (Hash) (defaults to: false)

    a customizable set of options

Returns:

  • (self)


648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'lib/plain_text/part.rb', line 648

def insert(ind, *rest, primitive: false)
  return insert_original_b4_part(ind, *rest) if primitive
  ipos = positive_array_index_checked(ind, self)
  if    rest.size.even? && (ipos > size - 1) && ipos.even?  # ipos.even? is equivalent to index_para?(ipos), i.e., "is the index for Paragraph?"
    raise ArgumentError, sprintf("number of arguments (%d) must be odd for index %s.", rest.size, ind)
  elsif rest.size.odd?  && (ipos <= size - 1)
    raise ArgumentError, sprintf("number of arguments (%d) must be even.", rest.size)
  end

  if ipos >= size
    rest = Array.new(ipos - size).map{|i| ""} + rest
    ipos = size
  end

  super(ipos, rest)
end

#inspectString

Returns:



456
457
458
# File 'lib/plain_text/part.rb', line 456

def inspect
  self.class.name + super
end

#last_significant_elementInteger?

The last significant (=non-empty) element.

If the returned value is non-nil and destructively altered, self changes.

Returns:

  • (Integer, nil)

    if self.empty? nil is returned.



222
223
224
225
# File 'lib/plain_text/part.rb', line 222

def last_significant_element
  (i = last_significant_index) || return
  self[i]
end

#last_significant_indexInteger?

Index of the last significant (=non-empty) element.

If every element is empty, 0 is returned.

Returns:

  • (Integer, nil)

    if self.empty? nil is returned.



232
233
234
235
236
237
238
# File 'lib/plain_text/part.rb', line 232

def last_significant_index
  return nil if empty?
  (0..(size-1)).to_a.reverse.each do |i|
    return i if self[i] && !self[i].empty?  # self for sanity
  end
  return 0
end

#map_boundary(**kwd, &bl) ⇒ Object

map method for boundaries only, returning a copied self.

If recursive is true (Default), any Boundaries in the descendant Parts are also handled.

If a Boundary is set nil or empty, along with the preceding Paragraph, the pair is removed from the returned instance in Default (:compact and :compacter options

Parameters:

  • recursive: (Hash)

    a customizable set of options

Returns:

  • as self

See Also:



251
252
253
# File 'lib/plain_text/part.rb', line 251

def map_boundary(**kwd, &bl)
  map_boundary_core(with_index: false, **kwd, &bl)
end

#map_boundary_with_index(**kwd, &bl) ⇒ Object

map method for boundaries only, providing also the index (always an odd number) to the block, returning a copied self.

Parameters:

  • recursive: (Hash)

    a customizable set of options

Returns:

  • as self



259
260
261
# File 'lib/plain_text/part.rb', line 259

def map_boundary_with_index(**kwd, &bl)
  map_boundary_core(with_index: true, **kwd, &bl)
end

#map_part(**kwd, &bl) ⇒ Object

map method for parts only, returning a copied self.

If recursive is true (Default), any Paragraphs in the descendant Parts are also handled.

If a Paragraph is set nil or empty, along with the following Boundary, the pair is removed from the returned instance in Default (:compact and :compacter options

Parameters:

  • recursive: (Hash)

    a customizable set of options

Returns:

  • as self

See Also:



274
275
276
# File 'lib/plain_text/part.rb', line 274

def map_part(**kwd, &bl)
  map_part_core(with_index: false, **kwd, &bl)
end

#map_part_with_index(**kwd, &bl) ⇒ Object

map method for parts only, providing also the index (always an even number) to the block, returning a copied self.

Parameters:

  • recursive: (Hash)

    a customizable set of options

Returns:

  • as self



282
283
284
# File 'lib/plain_text/part.rb', line 282

def map_part_with_index(**kwd, &bl)
  map_part_core(with_index: false, **kwd, &bl)
end

#normalize(recursive: true, ignore_array_boundary: true, compact: true, compacter: true) ⇒ Object

Non-destructive version of #normalize!

Parameters:

  • recursive: (Hash) (defaults to: true)

    a customizable set of options

  • ignore_array_boundary: (Hash) (defaults to: true)

    a customizable set of options

  • compact: (Hash) (defaults to: true)

    a customizable set of options

  • compacter: (Hash) (defaults to: true)

    a customizable set of options

Returns:

  • as self

See Also:



326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/plain_text/part.rb', line 326

def normalize(recursive: true, ignore_array_boundary: true, compact: true, compacter: true)
  # Trims pairs of consecutive Paragraph and Boundary of nil
  arall = to_a
  size_parity = (size.even? ? 0 : 1)
  if (compact || compacter) && (size > 0+size_parity)
    ((size-2-size_parity)..0).each do |i| 
      # Loop over every Paragraph
      next if i.odd?
      arall.slice! i, 2 if compact   &&  !self[i] && !self[i+1]
      arall.slice! i, 2 if compacter && (!self[i] || self[i].empty?) && (!self[i+1] || self[i+1].empty?)
    end
  end

  i = -1
  self.class.new(
    arall.map{ |ea|
      i += 1
      normalize_core(ea, i, recursive: recursive)
    } + (arall.size.odd? ? [Boundary.new('')] : [])
  )
end

#normalize!(recursive: true, ignore_array_boundary: true, compact: true, compacter: true) ⇒ self

Normalize the content, making sure it has an even number of elements

The even and odd number elements are, if bare Strings or Array, converted into Paeagraph and Boundary, or Part, respectively. If not, Exception is raised. Note nil is conveted into either an empty Paragraph or Boundary.

Parameters:

  • recursive: (Hash) (defaults to: true)

    a customizable set of options

  • ignore_array_boundary: (Hash) (defaults to: true)

    a customizable set of options

  • compact: (Hash) (defaults to: true)

    a customizable set of options

  • compacter: (Hash) (defaults to: true)

    a customizable set of options

Returns:

  • (self)


297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/plain_text/part.rb', line 297

def normalize!(recursive: true, ignore_array_boundary: true, compact: true, compacter: true)
  # Trim pairs of consecutive Paragraph and Boundary of nil
  size_parity = (size.even? ? 0 : 1)
  if (compact || compacter) && (size > 0+size_parity)
    ((size-2-size_parity)..0).each do |i| 
      # Loop over every Paragraph
      next if i.odd?
      slice! i, 2 if compact   &&  !self[i] && !self[i+1]
      slice! i, 2 if compacter && (!self[i] || self[i].empty?) && (!self[i+1] || self[i+1].empty?)
    end
  end

  i = -1
  map!{ |ea|
    i += 1
    normalize_core(ea, i, recursive: recursive)
  }
  insert_original_b4_part(size, Boundary.new('')) if size.odd?
  self
end

#partsArray<Part, Paragraph>

Returns an array of substantial parts (even-number-index parts), consisting of Part and/or Paragraph

Returns:

See Also:



353
354
355
356
# File 'lib/plain_text/part.rb', line 353

def parts
  select.with_index { |_, i| i.even? } rescue select.each_with_index { |_, i| i.even? } # Rescue for Ruby 2.1 or earlier
  # ret.freeze
end

#push(*rest) ⇒ self Also known as: append

Array#push

Parameters:

Returns:

  • (self)

See Also:



737
738
739
# File 'lib/plain_text/part.rb', line 737

def push(*rest)
  concat(rest)
end

#reparse(**kwd) ⇒ PlainText::Part

Non-destructive version of #reparse!

Parameters:

  • str (String)
  • rule: (Hash)

    a customizable set of options

  • name: (Hash)

    a customizable set of options

  • range: (Hash)

    a customizable set of options

Returns:



374
375
376
377
378
# File 'lib/plain_text/part.rb', line 374

def reparse(**kwd)
  ret = self.dup
  ret.reparse!(**kwd)
  ret
end

#reparse!(rule: PlainText::ParseRule::RuleConsecutiveLbs, name: nil, range: (0..-1)) ⇒ self

Reparses self or a part of it.

Parameters:

  • str (String)
  • rule: (Hash) (defaults to: PlainText::ParseRule::RuleConsecutiveLbs)

    a customizable set of options

  • name: (Hash) (defaults to: nil)

    a customizable set of options

  • range: (Hash) (defaults to: (0..-1))

    a customizable set of options

Returns:

  • (self)


365
366
367
368
# File 'lib/plain_text/part.rb', line 365

def reparse!(rule: PlainText::ParseRule::RuleConsecutiveLbs, name: nil, range: (0..-1))
  insert range.begin, self.class.parse((range ? self[range] : self), rule: rule, name: name)
  self
end

#slice!(arg1, *rest, primitive: false) ⇒ Object

Delete elements and return the deleted content or nil if nothing is deleted.

The number of elements to be deleted must be even.

Parameters:

  • arg1 (Integer, Range)
  • arg2 (Hash)

    a customizable set of options

  • primitive: (Hash) (defaults to: false)

    a customizable set of options

Returns:

  • as self or NilClass

Raises:

  • (ArgumentError)


674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
# File 'lib/plain_text/part.rb', line 674

def slice!(arg1, *rest, primitive: false)
  return slice_original_b4_part!(arg1, *rest) if primitive

  arg2 = rest[0]

  # Simple substitution to a single element
  raise ArgumentError, ERR_MSGS[:even_num] if !arg2 && !arg1.class.method_defined?(:exclude_end?)

  check_bracket_args_type_error(arg1, arg2)  # Args are now either (Int, Int) or (Range)

  if arg2
    size2delete = size2extract(arg1, arg2, ignore_error: true)  # maybe nil (if the index is too small).
    # raise ArgumentError, ERR_MSGS[:even_num] if arg2.to_int.odd?
    raise ArgumentError, ERR_MSGS[:even_num] if size2delete && size2delete.odd?
    raise ArgumentError, "odd index is not allowed as the starting Range for #{self.class.name}.  It must be even." if arg1.odd?  # Because the returned value is this class of instance.
    return super(arg1, *rest)
  end

  begin
    rang = normalize_index_range(arg1)
  rescue IndexError => err
    raise RangeError, err.message
  end

  raise RangeError if rang.begin < 0 || rang.end < 0

  return super(arg1, *rest) if (rang.begin > rang.end)  # nil or [] is returned

  size2delete = size2extract(rang, skip_renormalize: true)
  raise ArgumentError, ERR_MSGS[:even_num] if size2delete && size2delete.odd? 
  raise ArgumentError, "odd index is not allowed as the starting Range for #{self.class.name}.  It must be even." if rang.begin.odd?  # Because the returned value is this class of instance.
  super(arg1, *rest)
end

#squash_boundary_at!(index) ⇒ Boundary?

Emptifies all the Boundaries immediately before the Boundary at the index and squashes it to the one at it.

See #boundary_extended_at to view them.

Parameters:

  • index (Integer)

Returns:

  • (Boundary, nil)

    nil if a too large index is specified.



387
388
389
390
391
392
393
# File 'lib/plain_text/part.rb', line 387

def squash_boundary_at!(index)
  (i_pos = get_valid_ipos_for_boundary(index)) || return
  prt = self[i_pos-1]
  m = :emptify_last_boundary!
  self[i_pos] << prt.public_send(m) if prt.class.method_defined? m
  self[i_pos]
end

#squash_boundaryies!self

Wrapper of #squash_boundary_at! to loop over the whole PlainText::Part

Returns:

  • (self)


399
400
401
402
403
404
# File 'lib/plain_text/part.rb', line 399

def squash_boundaryies!
  each_boundary_with_index do |ec, i|
    squash_boundary_at!(i)
  end
  self
end

#subclass_nameString

Boundary sub-class name only

Make sure your class is a child class of Part Otherwise this method would not be inherited, obviously.

Examples:

class PlainText::Part
  class Section < self
    class Subsection < self; end  # It must be a child class!
  end
end
ss = PlainText::Part::Section::Subsection.new ["abc"]
ss.subclass_name  # => "Section::Subsection"

Returns:

See Also:



423
424
425
426
# File 'lib/plain_text/part.rb', line 423

def subclass_name
  printf "__method__=(%s)\n", __method__
  self.class.name.split(/\A#{Regexp.quote method(__method__).owner.name}::/)[1] || ''
end