Problem using OpenStruct with ERB

前端 未结 4 1810
旧时难觅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:13

    Fix to Problem:

    I stumbled upon this question when encountering the same type of error with similar code in Ruby 1.9.2.

    I'm new to Ruby so I can't explain what is happening. I continued to search online and found this blog post that has an approach that seems to work. After modifying your example to incorporate this approach I end up with the following, working, code:

    require 'ostruct'
    require 'erb'
    
    class ErbBinding < OpenStruct
        def get_binding
            return binding()
        end
    end
    
    data = {:bar => "baz"}
    vars = ErbBinding.new(data)
    
    template = "foo <%= bar %>"
    erb = ERB.new(template)
    
    vars_binding = vars.send(:get_binding)
    puts erb.result(vars_binding)
    

    Additional Information:

    When the code is run thru the IRB, I get:

    require 'ostruct'
    => true
    require 'erb'
    => true
    
    class ErbBinding < OpenStruct
        def get_binding
            return binding()
        end
    end
    => nil
    
    data = {:bar => "baz"}
    => {:bar=>"baz"}
    vars = ErbBinding.new(data)
    => #
    
    template = "foo <%= bar %>"
    => "foo <%= bar %>"
    erb = ERB.new(template)
    => #, @filename=nil>
    
    vars_binding = vars.send(:get_binding)
    => #
    puts erb.result(vars_binding)
    foo baz
    => nil
    

提交回复
热议问题