hostingerbironruby

Using ERB in IronRuby engine


I would like to use IronRuby with the ERB system to parse .erb format files and get the output.

In ruby this would be like:

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

But this just doesnt work in my IronRuby project. I get an exception about the erb file being missing... so I guess this is a libraries issue. I then initiated my Ruby engine with the paths to my IronRuby directories, which then throws a different exception:

allocator undefined for System::String

Solution

  • I had a similar issue, but I was providing the string to the script as a local variable through a scope. The local variable was a .NET CLR string, which is what caused the issue (please see here).

    The solution for me was to convert the string passed to ERB.new to a Ruby string using to_s.

    Here's an example (Ruby snippet):

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

    The C# Part which invoked the above script:

    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();
    

    In the above C# snippet, _bootstrapScript is a string which contains the Ruby snippet above.