Wednesday, July 05, 2006

Ruby : Pretty Code

I've been through many beginners tutorials for Ruby and I must say I really like this language. I think it's going to be very useful. The Pragmatic Programmers - Dave Thomas and Andy Hunt - give some good advice to learning a new language ... they say you must ask the question, "How will I know when I'm done?". I decided that my first "bout" of learning would be concluded when I had written my own program to prettify the text files I write for this blog! Usually I have to search and replace certain characters, manually add html tags for line breaks and code snippets, ensure that any preformatted line doesn't exceed 62 characters ... in short, a bit of a chore.



So here's the Ruby blog prettifier ... and of course, this blog post is the first to have been run through it! :)




class String

def subAfter str, ext
self[0..self.index(str)-1]+"."+ext
end

end

$column = 62
filename = ARGV[0].to_s

puts "Processing "+filename+"...\n"

File.open(filename, "r") do |file|

outFile = File.new(filename.subAfter(".","htm"), "w")

code = false;

file.each_line do |line|

if line.chomp == "@@@"

if code
outFile.puts "</pre></tt></blockquote>"
else
outFile.puts "<blockquote><pre><tt>"
end

code = !code;

else

if code

long = line
line = ""

while long.length > $column

space = long[0..$column].rindex(" ")

if space == nil
space = $column
end

line += long[0..space]+"\n"
long = long[space+1..-1]

end

line += long


line.gsub!(/</,"<")
line.gsub!(/>/,">")
else
line.gsub!(/\n\r|\n|\r/, "<br>")
end

outFile.puts line

end

end

outFile.close()

# This is a really long comment which I've added to show you
how the code prettifier neatly looks for the last space before
col 80 and splits the line :)
#_This_is_another_really_long_comment_which_I've_added_to_show_
you_how_the_code_prettifier_simply_cuts_the_line_if_there_are_n
o_spaces!

end

No comments: