Sha256: 3e3f74265bdca0ef501e6d727d30ccfdcc3c5019f7078f15f46c2eb486bb8218

Contents?: true

Size: 1.55 KB

Versions: 5

Compression:

Stored size: 1.55 KB

Contents

module Ruby2JS
  class Converter

    # (regexp
    #   (str "x")
    #   (regopt :i))

    handle :regexp do |*parts, opt|
      # remove "extended" from list of options
      extended = false
      opts = opt.children
      if opts.include? :x
        opts = opts - [:x]
        extended = true
      end

      # remove whitespace and comments from extended regular expressions
      if extended
        parts.map! do |part|
          if part.type == :str
            str = part.children.first 
            str = str.gsub(/ #.*/,'').gsub(/\s/,'')
            s(:str, str)
          else
            part
          end
        end
      end

      if parts.first.type == :str and parts.first.children[0].start_with?('^')
        opts = opts + [:m] unless opts.include? :m or opts.include? 'm'
      elsif parts.last.type == :str and parts.last.children[0].end_with?('$')
        opts = opts + [:m] unless opts.include? :m or opts.include? 'm'
      end

      # use slash syntax if there are few embedded slashes in the regexp
      if parts.all? {|part| part.type == :str}
        str = parts.map {|part| part.children.first}.join
        unless str.scan('/').length - str.scan("\\").length > 3
          return put "/#{ str.gsub('\\/', '/').gsub('/', '\\/') }/" +
            opts.join
        end
      end

      # create a new RegExp object
      put 'new RegExp('

      if parts.length == 1
        parse parts.first
      else
        parse s(:dstr, *parts)
      end

      unless opts.empty?
        put ", #{ opts.join.inspect}"
      end

      put ')'
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ruby2js-3.2.0 lib/ruby2js/converter/regexp.rb
ruby2js-3.1.2 lib/ruby2js/converter/regexp.rb
ruby2js-3.1.1 lib/ruby2js/converter/regexp.rb
ruby2js-3.1.0 lib/ruby2js/converter/regexp.rb
ruby2js-3.0.15 lib/ruby2js/converter/regexp.rb