use*_*363 3 ruby eval ruby-on-rails ruby-on-rails-3
我们要做的是将一大块erb代码存储在a中string然后执行代码run time.这是我们做的测试:
1. take out a chunk of the code from a working erb file and,
2. rewrite the erb file with eval.
Run Code Online (Sandbox Code Playgroud)
以下是取出的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 %>
Run Code Online (Sandbox Code Playgroud)
t()是国际化的翻译方法.
这是重写后的erb文件:
<table class="table table-striped">
<% code = find_config_const('task_log_view', 'projectx')%>
<%= eval(code)%>
</table>
Run Code Online (Sandbox Code Playgroud)
在重写之前,chunk of code介于两者之间<table>.Now变量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:
Run Code Online (Sandbox Code Playgroud)
上面的代码有什么问题?谢谢您的帮助.
eval 通过评估ruby代码来工作.
irb(main):001:0> eval('puts "Hello World"')
Hello World
=> nil
Run Code Online (Sandbox Code Playgroud)
转换erb模板应该用ERBclass 完成
irb(main):002:0> require 'erb'
irb(main):003:0> ERB.new('<%= "Hello World" %>').result
=> "Hello World"
Run Code Online (Sandbox Code Playgroud)
我的猜测是,code它实际上是一个包含ERB模板而不是ruby代码的字符串.
尽管如此,我认为这不是一个好方法.task.project.name可能来自可能来自用户输入的数据库.对此进行评估似乎不是一个好主意.
可能你可以正常解决你的问题 partials
| 归档时间: |
|
| 查看次数: |
4953 次 |
| 最近记录: |