【问题标题】:Using ERB in IronRuby engine在 IronRuby 引擎中使用 ERB
【发布时间】:2011-12-03 00:41:10
【问题描述】:

我想将 IronRuby 与 ERB 系统一起使用来解析 .erb 格式的文件并获取输出。

在 ruby​​ 中是这样的:

require "erb"
erbContent = "..."
return ERB.new(erbContent,0,"%<>").result

但这在我的 IronRuby 项目中不起作用。我得到一个关于 erb 文件丢失的异常......所以我猜这是一个库问题。然后,我使用 IronRuby 目录的路径启动了我的 Ruby 引擎,然后引发了一个不同的异常:

allocator undefined for System::String

【问题讨论】:

    标签: hosting erb ironruby


    【解决方案1】:

    我遇到了类似的问题,但我通过范围将字符串作为局部变量提供给脚本。 局部变量是一个 .NET CLR 字符串,这就是导致问题的原因 (please see here)。

    我的解决方案是使用 to_s 将传递给 ERB.new 的字符串转换为 Ruby 字符串。

    这是一个例子(Ruby sn-p):

    require 'erb'
    
    template = ERB.new(template_code.to_s)
    template.result(binding)
    

    调用上述脚本的C#部分:

    var scriptEngine = Ruby.CreateEngine();
    var templateCode = "my ERB template code goes here";
    // Pass the template code to the Ruby script through a scope
    var scope = _scriptEngine.CreateScope(new Dictionary<string, object>() 
                                                      { 
                                                        {"template_code", templateCode}
                                                      });
    
    var result scriptEngine.Execute(_boostrapScript, scope).ToString();
    

    在上述 C# sn-p 中,_bootstrapScript 是一个包含上述 Ruby sn-p 的字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多