File: js_regex.rb

package info (click to toggle)
ruby-js-regex 3.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 184 kB
  • sloc: ruby: 1,198; makefile: 3
file content (48 lines) | stat: -rw-r--r-- 1,134 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
# frozen_string_literal: true

# JsRegex converts ::Regexp instances to JavaScript.
#
# Usage:
#
# js_regex = JsRegex.new(my_ruby_regex)
# js_regex.to_h  # for use in 'new RegExp()'
# js_regex.to_s  # for direct injection into JavaScript
#
class JsRegex
  require_relative File.join('js_regex', 'conversion')
  require_relative File.join('js_regex', 'error')
  require_relative File.join('js_regex', 'version')
  require 'json'

  attr_reader :source, :options, :warnings, :target

  def initialize(ruby_regex, **kwargs)
    @source, @options, @warnings, @target = Conversion.of(ruby_regex, **kwargs)
  end

  def to_h
    { source: source, options: options }
  end

  def to_json(options = {})
    to_h.to_json(options)
  end

  def to_s
    "/#{source.empty? ? '(?:)' : source}/#{options}"
  end

  # @raise JsRegex::ConversionError
  def self.new!(ruby_regex, **kwargs)
    new(ruby_regex, fail_fast: true, **kwargs)
  end

  def self.compatible?(ruby_regex, **kwargs)
    new!(ruby_regex, **kwargs)
    true
  rescue ConversionError
    false
  end

  ConversionError = Class.new(StandardError).send(:include, JsRegex::Error)
end