4

我们正在尝试做的是在 a 中存储一段erb代码string,然后在run time. 这是我们做的一个测试:

1. take out a chunk of the code from a working erb file and, 
2. rewrite the erb file with eval. 

这是取出的 erb 代码块:

<tr>
      <th>#</th>
      <th><%= t('Date') %></th>
      <th><%= t('Project Name') %></th>
      <th><%= t('Task Name') %></th>
      <th><%= t('Log') %></th>
      <th><%= t('Entered By') %></th>

    </tr>

    <% @logs.each do |r| %>
        <tr>
          <td><%= r.id %></td>
          <td><%= (r.created_at + 8.hours).strftime("%Y/%m/%d")%></td>
          <td><%= prt(r, 'task.project.name') %></td>
          <td><%= prt(r, 'task.task_template.task_definition.name') %></td>
          <td><%= prt(r, :log) %></td>
          <td><%= prt(r, 'last_updated_by.name') %></td>

        </tr>
    <% end %>

t() 是国际化的翻译方法。

这是重写后的erb文件:

  <table class="table table-striped">
    <% code = find_config_const('task_log_view', 'projectx')%>
    <%= eval(code)%>

  </table>

在重写之前,chunk of code介于<table>. 现在变量code返回一个string代码块并eval执行代码块。但这是错误:

(eval):1: syntax error, unexpected '<'
(eval):4: syntax error, unexpected tIDENTIFIER, expecting $end
      <th><%= t('Project Name') %></th>
               ^

Extracted source (around line #6):

4:   <table class="table table-striped">
5:      <% code = find_config_const('task_log_view', 'projectx')%>
6:     <%= eval(code)%>
7: 
8:   </table>
9: 

上面的代码有什么问题?谢谢您的帮助。

4

1 回答 1

10

eval通过评估 ruby​​ 代码来工作。

irb(main):001:0> eval('puts "Hello World"')
Hello World
=> nil

而转换erb模板应该用ERB类来完成

irb(main):002:0> require 'erb'
irb(main):003:0> ERB.new('<%= "Hello World" %>').result
=> "Hello World"

我的猜测是,code它实际上是一个包含 ERB 模板而不是 ruby​​ 代码的字符串。

尽管如此,我认为这不是一个好方法。task.project.name可能来自可能来自用户输入的数据库。对此进行评估似乎不是一个好主意。

可能你可以正常解决你的问题partials

于 2013-08-07T21:59:10.377 回答