Ruby:erb抛出错误“`result”:无法将String转换为Integer(TypeError)“

快速背景:我正在设置一个快速而肮脏的模板方案,其中所有模板文件都命名为’* .erb’.填充数据驻留在yaml文件中.输出是带有模板名称的文件,减去’.erb’.

我没有用erb做太多工作,我得到错误“`result’:无法将String转换为Integer(TypeError)”……这对我来说没什么意义.

这是完成工作的类(generate_interface.rb):

#! /usr/bin/ruby

require 'yaml'
require 'erb'

class GenerateInterface
  def initialize(yamlfile)
    @yamlfile = yamlfile
    @erbfiles = Dir.glob("*.erb")
  end

  def gobutton
    # i -- interface. kept short because it's used all over the place in the erb files.
    i = YAML.load_file( @yamlfile )
    puts( "i: #{i.inspect}" )
    puts( "i['test_id']: #{i['test_id'].inspect}" )
    puts( "( i['test_id'] ).to_s: #{( i['test_id'] ).to_s}" )
    @outfile=@erbfiles.map do
      |erbfile|
      puts( "erbfile: #{erbfile.inspect}" )
      outfile = erbfile.gsub(/\.erb$/,"")
      puts( "outfile: #{outfile.inspect}" )
      template = File.open( erbfile, 'r' ) { |f| f.read }
      puts( "template: #{template.inspect}" )
      message = ERB.new(template, "%<>" )
      puts( "message: #{message.inspect}" )
      result=message.result
      puts( "result: #{result.inspect}" )
      File.open(outfile, 'w' ) { |f| f.write( message.result) }
    end
  end
end

yaml文件(test.yaml):

--- 
test_id: XXX123

模板文件(test.txt.erb):

Line 1
Line 2 test_id: <%= i['test_id'] %>
Line 3

驱动整个混乱的代码(test.rb):

#! /usr/bin/ruby

require "generate_interface"

test_interface = GenerateInterface.new( "test.yaml" )
test_interface.gobutton

最后,输出和错误消息:

$ruby -d test.rb
Exception `NoMethodError' at /usr/lib/ruby/1.8/rational.rb:78 - undefined method `gcd' for Rational(1, 2):Rational
i: {"test_id"=>XXX123}
i['test_id']: XXX123
( i['test_id'] ).to_s: XXX123
erbfile: "test.txt.erb"
outfile: "test.txt"
template: "Line 1\nLine 2 test_id: <%= i['test_id'] %>\nLine 3\n"
message: #<ERB:0xb74ac150 @src="_erbout = ''; _erbout.concat \"Line 1\\nLine 2 test_id: \"\n; _erbout.concat(( i['test_id'] ).to_s); _erbout.concat \"\\nLine 3\\n\"\n\n; _erbout", @safe_level="%<>", @filename=nil>
Exception `TypeError' at /usr/lib/ruby/1.8/erb.rb:715 - can't convert String into Integer
/usr/lib/ruby/1.8/erb.rb:715:in `result': can't convert String into Integer (TypeError)
    from /usr/lib/ruby/1.8/erb.rb:714:in `call'
    from /usr/lib/ruby/1.8/erb.rb:714:in `result'
    from ./generate_interface.rb:26:in `gobutton'
    from ./generate_interface.rb:17:in `map'
    from ./generate_interface.rb:17:in `gobutton'
    from test.rb:6

我认为_erbout.concat((i [‘test_id’]).to_s)有问题,但是当我明确打印(i [‘test_id’]).to_s时,我得到’XXX123′,这是我所期待的.

最佳答案 (您的generate_interface.rb粘贴错过了最终结束)

当前的问题是Erb.initialize的第二个参数是安全级别;第三个是修剪选项.您的修剪选项被解释为安全级别.

要解决这个问题,请改变

  message = ERB.new(template, "%<>" )

  message = ERB.new(template, nil, "%<>" )

第二个问题是变量i不能自动用于模板代码.要解决这个问题,你需要传递一个绑定,改变

  result = message.result

  result = message.result(binding)

在以下行中,将message.result更改为result

点赞