Class: JsRegex

Inherits:
Object
  • Object
show all
Defined in:
lib/js_regex.rb,
lib/js_regex/node.rb,
lib/js_regex/error.rb,
lib/js_regex/version.rb,
lib/js_regex/converter.rb,
lib/js_regex/conversion.rb,
lib/js_regex/second_pass.rb,
lib/js_regex/converter/base.rb,
lib/js_regex/converter/context.rb,
lib/js_regex/converter/set_converter.rb,
lib/js_regex/converter/meta_converter.rb,
lib/js_regex/converter/type_converter.rb,
lib/js_regex/converter/group_converter.rb,
lib/js_regex/converter/anchor_converter.rb,
lib/js_regex/converter/escape_converter.rb,
lib/js_regex/converter/literal_converter.rb,
lib/js_regex/converter/property_converter.rb,
lib/js_regex/converter/assertion_converter.rb,
lib/js_regex/converter/freespace_converter.rb,
lib/js_regex/converter/conditional_converter.rb,
lib/js_regex/converter/backreference_converter.rb,
lib/js_regex/converter/subexpression_converter.rb,
lib/js_regex/converter/unsupported_token_converter.rb

Overview

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

Defined Under Namespace

Modules: Converter, Error, SecondPass Classes: Conversion, Node

Constant Summary collapse

VERSION =
'3.7.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ruby_regex, options: nil) ⇒ JsRegex

Returns a new instance of JsRegex.



17
18
19
# File 'lib/js_regex.rb', line 17

def initialize(ruby_regex, options: nil)
  @source, @options, @warnings = Conversion.of(ruby_regex, options: options)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



15
16
17
# File 'lib/js_regex.rb', line 15

def options
  @options
end

#sourceObject (readonly)

Returns the value of attribute source.



15
16
17
# File 'lib/js_regex.rb', line 15

def source
  @source
end

#warningsObject (readonly)

Returns the value of attribute warnings.



15
16
17
# File 'lib/js_regex.rb', line 15

def warnings
  @warnings
end

Class Method Details

.new!(ruby_regex, options: nil) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/js_regex.rb', line 33

def self.new!(ruby_regex, options: nil)
  js_regex = new(ruby_regex, options: options)
  if js_regex.warnings.any?
    raise StandardError.new(
      "Could not fully convert the given regex #{ruby_regex.inspect}:\n" +
      js_regex.warnings.join("\n")
    ).extend(JsRegex::Error)
  end
  js_regex
end

Instance Method Details

#to_hObject



21
22
23
# File 'lib/js_regex.rb', line 21

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

#to_json(options = {}) ⇒ Object



25
26
27
# File 'lib/js_regex.rb', line 25

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

#to_sObject



29
30
31
# File 'lib/js_regex.rb', line 29

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