Sha256: 4de2f8728b265d827b43a715ec1c6acd9092f5b9297c6807c19c158c05945471

Contents?: true

Size: 1.43 KB

Versions: 7

Compression:

Stored size: 1.43 KB

Contents

# frozen_string_literal: true

# Opal seems to be missing the extended flag, this MonkeyPatch prevents errors.
if BBLib.in_opal?
  class Regexp
    EXTENDED = 2
  end
end

module BBLib
  REGEXP_MODE_HASH = {
    i: Regexp::IGNORECASE,
    m: Regexp::MULTILINE,
    x: Regexp::EXTENDED
  }.freeze

  REGEXP_OPTIONS = {
    i: [:ignore_case, :ignorecase, :i, :case_insensitive, Regexp::IGNORECASE],
    m: [:multiline, :multi_line, :m, Regexp::MULTILINE],
    x: [:extended, :x, Regexp::EXTENDED]
  }.freeze
end

class Regexp
  def self.from_s(str, *options, ignore_invalid: false)
    opt_map = options.map { |o| BBLib::REGEXP_OPTIONS.find { |k, v| o == k || o == k.to_s || v.include?(o) || v.include?(o.to_s.to_sym) }.first }.compact
    return Regexp.new(str, opt_map.inject(0) { |s, x| s += BBLib::REGEXP_MODE_HASH[x] }) if str.encap_by?('(') || !str.start_with?('/')
    str += opt_map.join
    mode = 0
    unless str.end_with?('/')
      str.split('/').last.chars.uniq.each do |l|
        raise ArgumentError, "Invalid Regexp mode: '#{l}'" unless ignore_invalid || BBLib::REGEXP_MODE_HASH[l.to_sym]
        mode += (BBLib::REGEXP_MODE_HASH[l.to_sym] || 0)
      end
      str = str[0..(str.rindex('/') || -1)]
    end
    Regexp.new(str.uncapsulate('/', limit: 1), mode)
  end
end

class String
  def to_regex(*options, ignore_invalid: false)
    Regexp.from_s(self, *options, ignore_invalid: ignore_invalid)
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
bblib-2.0.5 lib/bblib/core/util/regexp.rb
bblib-2.0.4 lib/bblib/core/util/regexp.rb
bblib-2.0.3 lib/bblib/core/util/regexp.rb
bblib-2.0.1 lib/bblib/core/util/regexp.rb
bblib-2.0.0 lib/bblib/core/util/regexp.rb
bblib-1.0.2 lib/string/regexp.rb
bblib-0.4.1 lib/string/regexp.rb