从.txt文件将变量插入ERB

时间:2012-05-02 22:24:04

标签: ruby-on-rails ruby ruby-on-rails-3

我构建了一个.erb文件,其中列出了一堆变量。

 <body>
    <h1>
        <%= header %>
    </h1>
    <p>
        <%= intro1 %>
    </p>
    <p>
        <%= content1 %>
    </p>
    <p>
        <%= content2 %>
    </p>
    <p>
        <%= content3 %>
    </p>
  </body>

然后我有一个包含变量的文本文件:

header=This is the header
intro1=This is the text for intro 1
content1=This is the content for content 1
content2=This is the content for content 2
content3=This is the content for content 3

我需要从文本文件中获取变量并将它们插入到.erb模板中。这样做的正确方法是什么?我只是想要一个ruby脚本,而不是整个rails网站。它仅适用于小页面,但需要多次完成。

由于

3 个答案:

答案 0 :(得分:3)

我会跳过txt文件,而是使用yml文件。

请访问此网站,了解有关如何执行该操作的更多信息:http://innovativethought.net/2009/01/02/making-configuration-files-with-yaml-revised/

答案 1 :(得分:3)

我认为很多人都是从“如何从存储位置获取价值?”来实现这一目标的。并忽略了问题的另一半:“我如何用内存中的一些Ruby变量替换<%= intro1 %>

这样的事情应该有效:

require 'erb'
original_contents = File.read(path_to_erb_file)
template = ERB.new(original_contents)

intro1 = "Hello World"
rendered_text = template.result(binding)

这里的binding意味着ERB在渲染时可以看到每个局部变量。 (从技术上讲,它不仅仅是变量,而是范围内可用的方法,以及其他一些东西)。

答案 2 :(得分:0)

我同意YML。如果你真的想要(或者有)使用文本文件,你可以这样做:

class MyClass
  def init_variables(text)
    text.scan(/(.*)=(.*)\n/).each do |couple|
      instance_variable_set("@" + couple[0], couple[1])
    end
  end
end

my_obj = MyClass.new
my_obj.init_variables("header=foo\ncontent1=bar")