From: "Ara.T.Howard" Date: 2005-09-12T03:28:49+09:00 Subject: Re: r4 - the simplest ruby pre-processor On Sun, 11 Sep 2005, Christian Neukirchen wrote: > "Ara.T.Howard" writes: > >> all this talk about pre-processors and erb got me thinking : what would it >> take to code up a ruby pre-procssors that could be used for any laguange. my >> first crack is 38 lines of ruby that pre-process any files on the command line >> (or stdin) using ruby as the macro language and a convenience function 'macro' >> which can be used to define ruby methods which return test that is used as >> output. functions declared this way need not do any explicit io. > > Alternative implementation ("r5"): > > def macro(name, &block) > Kernel.send(:define_method, name) { |*args| > puts block.call(args) > } > end > > send(($DEBUG ? "puts" : "eval"), ARGF.readlines.map { |line| > if line[0] == ?| > line[1..-1] > else > "puts #{line.chomp.dump}\n" > end > }.join) > > Happy hacking, a version which optionally interpolates - six lines, ergo r6 harp:~ > cat in | x = 42 using the -i switch i can interpolate x as #{ x } harp:~ > r6 in using the -i switch i can interpolate x as #{ x } harp:~ > r6 --interpolate in using the -i switch i can interpolate x as 42 harp:~ > cat r6 #! /usr/bin/env ruby def macro(m, &b); Kernel::send('define_method', m){|*a| puts b.call(a)}; end debug = $DEBUG || ENV['DEBUG'] || ARGV.delete('-d') || ARGV.delete('--debug') interp = $INTERPOLATE || ENV['INTERPOLATE'] || ARGV.delete('-i') || ARGV.delete('--interpolate') meth = debug ? 'puts' : 'eval' src = ARGF.readlines.map{|l| l =~ %r/^\s*\|(.*)/ ? $1 : (interp ? "puts \"#{ l.chomp }\"" : "puts #{ l.chomp.dump }")} send meth, src.join("\n") cheers. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | Your life dwells amoung the causes of death | Like a lamp standing in a strong breeze. --Nagarjuna ===============================================================================