Problem using OpenStruct with ERB

前端 未结 4 1808
旧时难觅i
旧时难觅i 2020-12-16 14:32

EDIT: forgot to include my environment info... Win7x64, RubyInstaller Ruby v1.9.1-p378

EDIT 2: just updated to v1.9.1, patch 429, a

4条回答
  •  粉色の甜心
    2020-12-16 15:20

    The problem is where the binding is being executed. The 1.8.7-way obj.send(:binding) does not work anymore (see issue2161), the environment must be the object itself. So use instance_eval:

    require 'ostruct'
    require 'erb'
    
    namespace = OpenStruct.new(:first => 'Salvador', :last => 'Espriu')
    template = 'Name: <%= first %> <%= last %>'
    ERB.new(template).result(namespace.instance_eval { binding })
    #=> Name: Salvador Espriu
    

    More about this issue in this answer.

提交回复
热议问题