Re: World's simplest code generator in ruby?

From: Mischa K. [mailto:[email protected]]

There is an .asp application on the internet which calls itself the
World’s simplest code generator it can be found here:
(secretGeek.net)

Here’s my hackish implementation in Ruby:

require ‘erb’
require ‘csv’

data = <<ENDDATA
tim, fruit, veg, he
sally, whiskey, cigars, she
jimmy, lager, crisps, he
jenny, fightin’, cussin’, she
ENDDATA

pattern = <<ENDPATTERN
$1 loves $2, but $4 hates $3
%if $2==“whiskey” then
(Hey $1, i also love $2!!!)
%end
ENDPATTERN

Output all variables that are at the start of the line

template = pattern.gsub( /^$(\d+)/, ‘<%=line[\1-1]%>’ )

Output all variables that are in the middle of a line

while template.gsub!( /^([^%].*)$(\d+)/, ‘\1<%=line[\2-1]%>’ )
end

Output all variables left over (in ruby code)

template.gsub!( /$(\d+)/, ‘line[\1-1]’ )

Create the ERB template

template = ERB.new( template, nil, ‘%’ )

Clean up the data to be true csv

data.gsub!( /,\s+/, ‘,’ )

Run the template once for each line

output = “”
CSV::Reader.parse( data ){ |line|
output << template.result( binding )
}

puts output
#=> tim loves fruit, but he hates veg
#=> sally loves whiskey, but she hates cigars
#=> (Hey sally, i also love whiskey!!!)
#=> jimmy loves lager, but he hates crisps
#=> jenny loves fightin’, but she hates cussin’