summaryrefslogtreecommitdiff
path: root/spec/ruby/language/regexp/interpolation_spec.rb
blob: ed0b7247632a9ea89b2ee749deb8afaf8284c2db (plain)
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
49
50
51
52
53
54
55
56
57
58
require_relative '../../spec_helper'
require_relative '../fixtures/classes'

describe "Regexps with interpolation" do

  it "allows interpolation of strings" do
    str = "foo|bar"
    /#{str}/.should == /foo|bar/
  end

  it "allows interpolation of literal regexps" do
    re = /foo|bar/
    /#{re}/.should == /(?-mix:foo|bar)/
  end

  it "allows interpolation of any object that responds to to_s" do
    o = Object.new
    def o.to_s
      "object_with_to_s"
    end
    /#{o}/.should == /object_with_to_s/
  end

  it "allows interpolation which mixes modifiers" do
    re = /foo/i
    /#{re} bar/m.should == /(?i-mx:foo) bar/m
  end

  it "allows interpolation to interact with other Regexp constructs" do
    str = "foo)|(bar"
    /(#{str})/.should == /(foo)|(bar)/

    str = "a"
    /[#{str}-z]/.should == /[a-z]/
  end

  it "gives precedence to escape sequences over substitution" do
    str = "J"
    /\c#{str}/.to_s.should == '(?-mix:\c#' + '{str})'
  end

  it "throws RegexpError for malformed interpolation" do
    s = ""
    -> { /(#{s}/ }.should raise_error(RegexpError)
    s = "("
    -> { /#{s}/ }.should raise_error(RegexpError)
  end

  it "allows interpolation in extended mode" do
    var = "#comment\n  foo  #comment\n  |  bar"
    (/#{var}/x =~ "foo").should == (/foo|bar/ =~ "foo")
  end

  it "allows escape sequences in interpolated regexps" do
    escape_seq = %r{"\x80"}n
    %r{#{escape_seq}}n.should == /(?-mix:"\x80")/n
  end
end