Class: ZodRails::Mapping::RegexpMapper

Inherits:
Object
  • Object
show all
Defined in:
lib/zod_rails/mapping/regexp_mapper.rb

Constant Summary collapse

UNSUPPORTED_TOKENS =
%w[\\K \\R (?> (?~].freeze

Class Method Summary collapse

Class Method Details

.call(regex) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/zod_rails/mapping/regexp_mapper.rb', line 8

def self.call(regex)
  if unsupported?(regex)
    ZodRails.logger.warn("ZodRails: Skipping regexp with Ruby-only semantics: #{regex.inspect}")
    return nil
  end

  pattern = regex.source
                 .gsub("\\A", "^")
                 .gsub("\\z", "(?![\\s\\S])")
                 .gsub("\\Z", "(?=(?:\\n)?(?![\\s\\S]))")
  flags = flags_for(regex)
  args = [JSON.generate(pattern), (JSON.generate(flags) unless flags.empty?)].compact
  "new RegExp(#{args.join(", ")})"
end