Yak Shaving: optimizing brain usage for code snippets

So you checked out how TextMate has all those wonderful snippets for every possible piece of code you could think of (and how now Emacs also does!), but you’re having second thoughts on wether it pays off to memorizing all those little abreviations and their meanings?

Not anymore!

With the cute one-liner below, you can fire up irb on your snippets directory and see instantly the TOP 5 winners in characters-saved / characters-typed !! Pretty neat huh? ;)

Here’s an example:

$ cd ~/.emacs.d/yasnippet/snippets/text-mode/ruby-mode
$ irb
irb(main):019:0> Dir['*'].map {|f| [f,File.read(f).reject{|s| s =~ /^#/}.join.size.to_f/f.size]}.sort {|a,b| b.last <=> a.last}.first(5).each {|f| puts "####" + f.first,File.read(f.first), "\n" *2}
####w
#name : attr_writer ...
# --
attr_writer :${attr_names}

####r
#name : attr_reader …
# –
attr_reader :${attr_names}

####mm
#name : def method_missing … end
# –
def method_missing(method, *args)
$0
end

####am
#name : alias_method new, old
# –
alias_method :${new_name}, :${old_name}

####bm
#name : Benchmark.bmbm(…) do … end
# –
Benchmark.bmbm(${1:10}) do |x|
$0
end

=> [["w", 26.0], ["r", 26.0], ["mm", 21.0], ["am", 19.5], ["bm", 19.5]]

It would probably be nice also to consider how much typing it saves you by mirroring variable names and stuff… And also how frequent that particular construct actually is in your code… Come to think of it, this one-liner is pretty useless, but at least picking an arbitrary 5 or 6 snippets to add to your dynamic cheatsheet is better than trying to randomly memorize them.

In case you didn’t catch it, here it is in full color (and we discover wordpress doesn’t use a full parser for syntax highlighting, what a shame :P):


Dir['*'].map {|f| [f,File.read(f).reject{|s| s =~ /^#/}.join.size.to_f/f.size]}.sort {|a,b| b.last => a.last}.first(5).each {|f| puts "####" + f.first,File.read(f.first), "\n" *2}

One Response to “Yak Shaving: optimizing brain usage for code snippets”

  1. A little Emacs experiment « cmarcelo Says:

    [...] he found out about yasnippet that allowed the creation of mini-templates that are triggered by short strings and then using TAB [...]


Leave a Reply