Created
January 20, 2011 00:01
-
-
Save sflinter/787145 to your computer and use it in GitHub Desktop.
This is a simple program that reads in a Ruby ERB file, and parses it as an XHTML file. Specifically, it makes a decent attempt at converting the ERB tags (<% %> and <%= %>) to XML tags (<erb-disp/> and <erb-eval/> respectively. Once the document has b
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'nokogiri' | |
# This is a simple program that reads in a Ruby ERB file, and parses | |
# it as an XHTML file. Specifically, it makes a decent attempt at | |
# converting the ERB tags (<% %> and <%= %>) to XML tags (<erb-disp/> | |
# and <erb-eval/> respectively. | |
# | |
# Once the document has been parsed, it will be validated and any | |
# error messages will be displayed. | |
# | |
# More complex option and error handling is left as an exercise to the user. | |
abort 'Usage: erb.rb <filename>' if ARGV.empty? | |
filename = ARGV[0] | |
begin | |
doc = "" | |
File.open(filename) do |file| | |
puts "\n*** Parsing #{filename} ***\n\n" | |
file.read(nil, s = "") | |
# Substitute the standard ERB tags to convert them to XML tags | |
# <%= ... %> for <erb-disp> ... </erb-disp> | |
# <% ... %> for <erb-eval> ... </erb-eval> | |
# | |
# Note that this won't work for more complex expressions such as: | |
# <a href=<% @some_object.generate_url -%> >link text</a> | |
# Of course, this is not great style, anyway... | |
s.gsub!(/<%=(.+?)%>/m, '<erb-disp>\1</erb-disp>') | |
s.gsub!(/<%(.+?)%>/m, '<erb-eval>\1</erb-eval>') | |
doc = Nokogiri::XML(s) do |config| | |
# put more config options here if required | |
# config.strict | |
end | |
end | |
puts doc.to_xhtml(:indent => 2, :encoding => 'UTF-8') | |
puts "Huzzah, no errors!" if doc.errors.empty? | |
# Otherwise, print each error message | |
doc.errors.each { |e| puts "Error at line #{e.line}: #{e}" } | |
rescue | |
puts "Oops! Cannot open #{filename}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Love it! I actually put it inside an html comment to avoid interference between anything at the ERB that would resamble html