Skip to content

Instantly share code, notes, and snippets.

@glurp
Created December 11, 2012 12:16
Show Gist options
  • Select an option

  • Save glurp/4258136 to your computer and use it in GitHub Desktop.

Select an option

Save glurp/4258136 to your computer and use it in GitHub Desktop.
convert ruby code formated 'a la python' to regular ruby code
####
#### transform ruby/dsl code with tabulation
#### block (a la python)to ruby block
####
if ARGV.size!=1 || !File.exists?(ARGV[0])
puts "Usage: > ruby #{$0} filename"
exit(1)
end
last_indent,no,h,last_key=0,0,{},""
sbegin=%w{
class module def
begin rescue finaly
if unless while case until
}.inject({}) { |h,k| h[k]=true;h }
puts File.read(ARGV.shift)
.gsub(/\n\s*\n/,"\n")
.gsub(/\n\s*#[^\n]\n/,"\n")
.concat("\n;")
.split(/(\s*)([^\n]*)\n?/)
.each_slice(3)
.map { |x,start,line|
next unless start && line
puts "'%s'%-50s %d / '%s'" % [start,line,start.size,last_key] if $DEBUG
indent=start.size
delta=last_indent-indent
line0=line
if delta>0
line = ((1..delta).each.inject("") {|s,i| s<<start+("\t"*(delta-i))+"end\n"})+start+line
end
h[no]=1 if delta==-1 && (! sbegin[last_key]) && line.split('|').size<2
raise("error indentation line #{no}") if delta<-1
last_key=line0.scan(/\w+/)[0]
last_indent=indent
no+=1
p line if $DEBUG
start+line+" __##{no}#__ "
}.join("\n")
.gsub(/__#\d+#__/) { |m| n=m[3..-4].to_i ; h[n] ? "do" : "" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment