I built a .erb file that has a bunch of variables listed in it.
<body>
<h1>
<%= header %>
</h1>
<p>
<%= intro1 %>
</p>
<p>
<%= content1 %>
</p>
<p>
<%= content2 %>
</p>
<p>
<%= content3 %>
</p>
</body>
Then I have a text file with the variables:
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
I need to take the variables from the text file and insert them into the .erb template. What is the proper way to do this? I am thinking just a ruby script, rather than an entire rails site. It is only for a small page, but needs to be done multiple times.
Thanks
I would skip the txt file, and instead go with a yml file.
Check this site out for a little more info on how to do it: http://innovativethought.net/2009/01/02/making-configuration-files-with-yaml-revised/
I think a lot of people have come at this from the "how do I get the values out of where they are stored?" and have ignored the other half of the question: "How do I replace <%= intro1 %>
with some Ruby variable I have in memory?
Something like this should work:
require 'erb'
original_contents = File.read(path_to_erb_file)
template = ERB.new(original_contents)
intro1 = "Hello World"
rendered_text = template.result(binding)
the binding
thing here means that every local variable can be seen inside by ERB when it's rendered. (Technically, it's not just variables, but methods available in the scope, and some other things).
I agree about YML. If you really want (or have) to use a text file, you can do something like that :
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.