Skip to content

Instantly share code, notes, and snippets.

@sflinter
Created January 20, 2011 00:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sflinter/787145 to your computer and use it in GitHub Desktop.
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
#!/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
@viniciusnz
Copy link

Love it! I actually put it inside an html comment to avoid interference between anything at the ERB that would resamble html

  def keep_erbs(value)
    value = value.gsub(/<%=(.+?)%>/m, '<erb-disp><!--\1--></erb-disp>')
    value = value.gsub(/<%(.+?)%>/m, '<erb-eval><!--\1--></erb-eval>')
    value = yield(value)
    value = value.gsub(/<erb-eval><!--(.+?)--><\/erb-eval>/m) {|current_value| '<%' + CGI.unescapeHTML(Regexp.last_match[1]) + '%>'}
    value = value.gsub(/<erb-disp><!--(.+?)--><\/erb-disp>/m) {|current_value| '<%=' + CGI.unescapeHTML(Regexp.last_match[1]) + '%>'}
    value
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment