You are not logged in.
Hi folks,
since I have a lot of time recently, I decided to create a little (non-dynamic) website with HTML and CSS.
So, when I began writing I noticed that there is a lot of "typing overhead" what really went on my nerves.
Be it as this may... I was thinking about how I could shorten the whole process of writing HTML-code.
I began writing a little ruby-script, wich reads a HTML file line by line, searches for a certain pattern, interprets this pattern and generates HTML-code out of it.
I hope you get what I mean. Here is the code (it's still experimental... )
# Command class - contains the "template"-code
class Commands
# generate a list
def Commands.list(args)
s = "<ul>\n"
args.each { |arg| s += "<li>#{arg}</li>\n" }
s += "</ul>\n"
end
# generate a headline
def Commands.h2 (args)
"<h2>#{args.join(" ")}</h2>"
end
# generate an image
def Commands.img(args)
"<img src='#{args[0]}' width='#{args[1]}' height='#{args[2]}'/>"
end
end
# Searches for pattern and executes them
def execute_rubyfoo(content)
content = content.map { |line| line.strip }
new_content = content
success = 0
errors = 0
puts "Generating..."
new_content.each_with_index { |line, i|
# line matches pattern
if line =~ /^\$\$\s*rfoo.*/
command = new_content[i].sub(/\$\$rfoo\s*/, "")
command = command.sub(/\s*\$\$/, "")
command = command.split(" ")
begin
method = Commands.method(command[0])
new_content[i] = method.call command[1..-1]
success += 1
rescue NameError => e
puts "--> Line #{i + 1}: Command not found: #{command[0]}"
errors += 1
end
end
}
puts "\n---"
puts "Finished: #{success} successfully, #{errors} errors."
new_content
end
file = File.new("foo.html", "r+")
new_content = execute_rubyfoo(file.readlines)
file.close
new_file = File.new("foo.html.bla", "w+")
new_file.puts new_content
new_file.close
An example HTML-file could look like that:
<html>
<body>
<h1>Hallo</h1>
$$rfoo list 1 2 3 4 5$$
$$rfoo h2$$
$$rfoo img bla.png 100 100$$
</body>
</html>
And a generated HTML-file like that:
<html>
<body>
<h1>Hallo</h1>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<h2>foo</h2>
<img src='bla.png' width='100' height='100'/>
</body>
</html>
So, now what I want to know is:
What do you think about this idea in general and the way I implemented it? Is there already something like that?
Thanks,
g0ju
Offline
Offline
Ah, I suspected it... like many times before somebody already did it.
Nonetheless it was a nice practice. Thanks for the links.
Offline
ERB is even part of the standard ruby libraries. See the Notes for other alternatives.
I have to admit that I'm guilty of reinventing that wheel, too
Last edited by hbekel (2009-09-22 09:04:57)
Offline