从.txt文件将变量插入ERB

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

 

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

 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网站。 它仅适用于小页面,但需要多次完成。

谢谢

我想很多人都是从“如何从存储位置中获取价值?”来实现这一目标的。 并忽略了问题的另一半:“我如何用内存中的一些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在渲染时可以看到每个局部变量。 (从技术上讲,它不仅仅是变量,而是范围中可用的方法,以及其他一些东西)。

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

请访问此站点以获取有关如何执行此操作的更多信息: http : //innovativethought.net/2009/01/02/making-configuration-files-with-yaml-revised/

我同意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")