From fcbf63e62c627deae76c1b8cb8c0876c536ed811 Mon Sep 17 00:00:00 2001 From: Jari Vetoniemi Date: Mon, 16 Mar 2020 18:49:26 +0900 Subject: Fresh start --- jni/ruby/sample/ripper/ruby2html.rb | 112 ++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 jni/ruby/sample/ripper/ruby2html.rb (limited to 'jni/ruby/sample/ripper/ruby2html.rb') diff --git a/jni/ruby/sample/ripper/ruby2html.rb b/jni/ruby/sample/ripper/ruby2html.rb new file mode 100644 index 0000000..8f64f5a --- /dev/null +++ b/jni/ruby/sample/ripper/ruby2html.rb @@ -0,0 +1,112 @@ +#!/usr/bin/env ruby +# $originalId: ruby2html.rb,v 1.2 2005/09/23 22:53:47 aamine Exp $ + +TEMPLATE_LINE = __LINE__ + 2 +TEMPLATE = <<-EndTemplate + + + + +<% if css %> + +<% end %> + <%= File.basename(f.path) %> + + +
+<%
+    if print_line_number
+      Ruby2HTML.compile(f).each_with_index do |line, idx|
+%><%= sprintf('%4d  %s', idx+1, line) %><%
+      end
+    else
+%><%= Ruby2HTML.compile(f) %><%
+    end
+%>
+
+ + +EndTemplate + +require 'ripper' +require 'stringio' +require 'cgi' +require 'erb' +require 'optparse' + +def main + encoding = 'us-ascii' + css = nil + print_line_number = false + parser = OptionParser.new + parser.banner = "Usage: #{File.basename($0)} [-l] [...]" + parser.on('--encoding=NAME', 'Character encoding [us-ascii].') {|name| + encoding = name + } + parser.on('--css=URL', 'Set a link to CSS.') {|url| + css = url + } + parser.on('-l', '--line-number', 'Show line number.') { + print_line_number = true + } + parser.on('--help', 'Prints this message and quit.') { + puts parser.help + exit 0 + } + begin + parser.parse! + rescue OptionParser::ParseError => err + $stderr.puts err + $stderr.puts parser.help + exit 1 + end + puts ruby2html(ARGF, encoding, css, print_line_number) +end + +class ERB + attr_accessor :lineno + + remove_method :result + def result(b) + eval(@src, b, (@filename || '(erb)'), (@lineno || 1)) + end +end + +def ruby2html(f, encoding, css, print_line_number) + erb = ERB.new(TEMPLATE, nil, '>') + erb.filename = __FILE__ + erb.lineno = TEMPLATE_LINE + erb.result(binding()) +end + +class Ruby2HTML < Ripper::Filter + def Ruby2HTML.compile(f) + buf = StringIO.new + Ruby2HTML.new(f).parse(buf) + buf.string + end + + def on_default(event, tok, f) + f << CGI.escapeHTML(tok) + end + + def on_kw(tok, f) + f << %Q[#{CGI.escapeHTML(tok)}] + end + + def on_comment(tok, f) + f << %Q[#{CGI.escapeHTML(tok.rstrip)}\n] + end + + def on_tstring_beg(tok, f) + f << %Q[#{CGI.escapeHTML(tok)}] + end + + def on_tstring_end(tok, f) + f << %Q[#{CGI.escapeHTML(tok)}] + end +end + +if $0 == __FILE__ + main +end -- cgit v1.2.3