Diego Alvarez
Diego Alvarez

Reputation: 2847

Ruby metaprogramming - Multi line strings that doesn't try to evaluate the inner #{}

Is there any way to make multi line strings that doesn't try to evaluate the inner #{} ?

I want the following:

doc <<-DOC    
    describe "should get sysdate on test: #{test_name}" do
        it "should get SYSDATE" do
            conx_bd.sysdate.should_not == NULL
        end
    end    
DOC

to create a string (doc) with this content: (is for metaprogramming)

describe "should get sysdate on test: #{test_name}" do
    it "should get SYSDATE" do
        conx_bd.sysdate.should_not == NULL
    end
end    

i'm getting this error:

NameError: undefined local variable or method `test_name' for main:Object

if a surround the heredoc identifier with single quotes, i get this error if the string has for example a require

doc <<'-DOC'
require "spec_helper.rb" # conexión oracle

describe "should get sysdate on test: #{test_name}" do
    it "should get SYSDATE" do
        conx_bd.sysdate.should_not == NULL
    end
end  

DOC

error:

LoadError: no such file to load -- spec_helper

tks

EDIT: Tks for your support, i get 2 possible solutions from the answers.

First i have an error defining the multi line string

doc <<-DOC should be <<-doc 
  1. scape # with \

    <<-doc
    describe "should get sysdate on test: #{test_name}" do it "should get SYSDATE" do conx_bd.sysdate.should_not == NULL end end
    doc

  2. Surround the heredoc identifier with single quotes

    <<-'doc'
    describe "should get sysdate on test: #{test_name}" do it "should get SYSDATE" do conx_bd.sysdate.should_not == NULL end end
    doc

Upvotes: 2

Views: 204

Answers (2)

sawa
sawa

Reputation: 168081

Surround the heredoc identifier with single quotes.

doc <<-'DOC'    
    describe "should get sysdate on test: #{test_name}" do
        it "should get SYSDATE" do
            conx_bd.sysdate.should_not == NULL
        end
    end    
DOC

Edit I was wrong about the relative position of the single quote opening and the hyphen. steenslag was right. Fixed.

Upvotes: 3

juanpavergara
juanpavergara

Reputation: 1531

Try the with the escape character before #. The escape character is \.

Upvotes: 2

Related Questions