Monday, November 22, 2010

hamrbl: write ruby with python style whitespace (a haml hack)

Did you ever wish your code looked more like your haml?

Did you ever wonder what ruby would be like with python style significant whitespace?

Without further ado, I present hamrbl.rb

require 'rubygems'
require 'haml'
# Put a - char on each line in just the right place.
# (Need to remove blank lines too, they cause problems)
haml_source = File.read($0).gsub(/\n+/,"\n").gsub(/^\s*/,'\&-')
begin
# Run the file with haml
Haml::Engine.new(haml_source).render
rescue Exception => e
# Spit out the haml source to make it easier to find your error
puts "FAILED!\n#{haml_source}"
raise e
end
exit
# Here's a one line version :)
# Haml::Engine.new(File.read($0).gsub(/\n+/,"\n").gsub(/^\s*/,'\&-')).render; exit
view raw hamrbl.rb hosted with ❤ by GitHub
#!/usr/bin/ruby -r hamrbl
# Just a test of hamlrb.rb
module Singing
def sing(count=1)
count.times do |i|
if %w[tweety bigbird].include? @name.downcase
puts "#{@name}: 'tweet tweet #{i+1}'"
else
puts "#{@name}: 'la la la #{i+1}'"
class Singer
include Singing
def initialize(name)
@name = name
# comments are okay :)
Singer.new('Thom').sing(2)
Singer.new('Tweety').sing
view raw test.rb hosted with ❤ by GitHub
$ ls -l
total 24
-rw-r--r-- 1 simon staff 232 17 Nov 21:13 hamrbl.rb
-rwxr-xr-x 1 simon staff 433 17 Nov 21:56 test.rb
$ ./test.rb
Thom: 'la la la 1'
Thom: 'la la la 2'
Tweety: 'tweet tweet 1'
$
view raw zzoutput hosted with ❤ by GitHub

Surprisingly the syntax highlighting works fine in vim and github. :)

Ps, it's pronounced "hammerable"

Disclaimer: This is for amusement purposes only. It is almost certainly a terrible misuse of Haml :).

No comments: