Ruby 从数据库中插入字符串

Ruby 从数据库中插入字符串,ruby,string-interpolation,Ruby,String Interpolation,例如: t = Test.new t.test_string = "\#{foo} and \#{bar}" t.save 然后我想在我的方法中插入这个字符串 我已经尝试了几种选择: ERB.new foo='Hello' 酒吧=‘世界’ ERB.new(t.test_字符串)。结果 它不工作,测试字符串打印为“\\{foo}和\{bar}” 只有在打印时不带转义符号“\”时,它才能工作 ERB.new("#{foo} and #{bar}").result => "Hell

例如:

t = Test.new
t.test_string = "\#{foo} and \#{bar}"
t.save
然后我想在我的方法中插入这个字符串

我已经尝试了几种选择:

  • ERB.new

    foo='Hello'
    酒吧=‘世界’
    ERB.new(t.test_字符串)。结果
    

  • 它不工作,测试字符串打印为
    “\\{foo}和\{bar}”

    只有在打印时不带转义符号“\”时,它才能工作

        ERB.new("#{foo} and #{bar}").result
     => "Hello and World"
    
    但是我怎样才能使它程序化呢

  • eval

    foo='Hello'
    酒吧=‘世界’
    eval''+t.test_string+''”

  • 它可以工作,但不安全


    我还有其他选择吗?或者如何使新的工作?

    也许我不太理解你的需要。
    这就是你要找的吗

    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
    
    需要“erb”
    erb_template=erb.new('foo=2+2='))
    bar='baz'
    erb_template.result(binding)#=>foo等于baz,2+2=4
    

    binding
    方法捕获您当前的作用域,以便ERB在此作用域中呈现模板。

    “如何使ERB.new工作”-如果您认为使用ERB自动安全,请使用适当的ERB语法(
    ),然后知道
    ERB#结果
    是通过
    eval
    实现的。没有人是安全的()