zolter
zolter

Reputation: 7160

Interpolate string from database

For example:

t = Test.new
t.test_string = "\#{foo} and \#{bar}"
t.save

And then I want to interpolate this string in one of my method.

I am already tried several options:

  1. ERB.new

    foo = 'Hello' bar = 'World' ERB.new(t.test_string).result

It does not work, test_string print as "\#{foo} and \#{bar}".

It work only if I print it without escape symbol '\'.

    ERB.new("#{foo} and #{bar}").result
 => "Hello and World"

But how can I make it programatic?

  1. eval

    foo = 'Hello' bar = 'World' eval '"' + t.test_string + '"'

It works but it is not safe.

Do I have any other options? Or how to make ERB.new work?

Upvotes: 1

Views: 54

Answers (1)

Aleksey
Aleksey

Reputation: 2309

Maybe I don't quite understand your needs.
Is it what you are looking for?

require 'erb'

erb_template = ERB.new('foo equals <%= bar %> and 2 + 2 = <%= 2 + 2 %>')
bar = 'baz'
erb_template.result(binding) # => foo equals baz and 2 + 2 = 4

binding method captures your current scope so ERB is rendering template in this scope.

Upvotes: 1

Related Questions