Module: ToRegex::StringMixin

Included in:
String
Defined in:
lib/wayback_machine_downloader/to_regex.rb

Constant Summary collapse

INLINE_OPTIONS =
/[imxnesu]*/i.freeze
REGEXP_DELIMITERS =
{
  '%r{' => '}'.freeze,
  '/' => '/'.freeze
}.freeze
REGEX_FLAGS =
{
  ignore_case: Regexp::IGNORECASE,
  multiline: Regexp::MULTILINE,
  extended: Regexp::EXTENDED
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.literal?(str) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/wayback_machine_downloader/to_regex.rb', line 18

def literal?(str)
  REGEXP_DELIMITERS.none? { |start, ending| str.start_with?(start) && str.match?(/#{ending}#{INLINE_OPTIONS}\z/) }
end

Instance Method Details

#as_regexp(options = {}) ⇒ Object

Return arguments that can be passed to ‘Regexp.new`

Raises:

  • (ArgumentError)

See Also:

  • to_regexp


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/wayback_machine_downloader/to_regex.rb', line 40

def as_regexp(options = {})
  raise ArgumentError, '[to_regexp] Options must be a Hash' unless options.is_a?(Hash)
  
  str = self
  return if options[:detect] && str.empty?

  if should_treat_as_literal?(str, options)
    content = Regexp.escape(str)
  elsif (delim_set = extract_delimiters(str))
    content, options = parse_regexp_string(str, delim_set, options)
    return unless content
  else
    return
  end

  build_regexp_args(content, options)
end

#to_regex(options = {}) ⇒ Object

Get a regex back

Without :literal or :detect, ‘“foo”.to_regex` will return nil.

Parameters:

  • options (optional, Hash) (defaults to: {})

Options Hash (options):

  • :literal (true, false)

    Treat meta characters and other regexp codes as just text; always return a regexp

  • :detect (true, false)

    If string starts and ends with valid regexp delimiters, treat it as a regexp; otherwise, interpret it literally

  • :ignore_case (true, false)

    /foo/i

  • :multiline (true, false)

    /foo/m

  • :extended (true, false)

    /foo/x

  • :lang (true, false)

    /foo/



34
35
36
37
# File 'lib/wayback_machine_downloader/to_regex.rb', line 34

def to_regex(options = {})
  args = as_regexp(options)
  args ? Regexp.new(*args) : nil
end