Class: BBLib::Splitter

Inherits:
Object
  • Object
show all
Includes:
Effortless
Defined in:
lib/bblib/core/classes/splitter.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Effortless

#_attrs, included

Class Method Details

.split(string, *delimiters, **opts) ⇒ Object



17
18
19
# File 'lib/bblib/core/classes/splitter.rb', line 17

def self.split(string, *delimiters, **opts)
  new(opts.except(:count).merge(delimiters: delimiters)).split(string, opts.delete(:count))
end

Instance Method Details

#split(string, count = nil) ⇒ Object



21
22
23
24
25
26
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
60
61
# File 'lib/bblib/core/classes/splitter.rb', line 21

def split(string, count = nil)
  return string if count == 1
  index = 0
  splits = 1
  [].tap do |array|
    until index >= string.size
      sub_string = string[index..-1]
      escaped    = string[index - 1] == escape_char if ignore_escaped_chars?

      if inside?
        open_match = match(sub_string, current_expression)
        close_match = match(sub_string, expressions[current_expression])
        if current_start != index && close_match && !escaped
          self.inside = false if (self.current_depth -= 1).zero?
        elsif open_match && !escaped
          self.current_depth += 1
          self.part += open_match
          index += open_match.size
          next
        end
      elsif expression = check_expressions(sub_string)
        self.inside = true
        self.current_start = index
        self.current_expression = expression
        self.current_depth += 1
        self.part += current_expression_match
        index += current_expression_match.size
        next
      elsif !escaped? && (count.nil? || splits < count) && delimiter_check(sub_string)
        array << self.part
        splits += 1
        self.part = ''
        index += current_delimiter_match.size
        next
      end
      self.part += string[index].to_s
      index += 1
    end
    array << self.part
  end
end