Last Updated: February 25, 2016
·
1.023K
· kgrz

Code notes using Rake, Zsh

[Edit: works only if there is no Rakefile inside the project]

If you have installed the rake gem, and have some .rake files at ~/.rake, the tasks inside these files get automatically loaded by the rake program. This feature can be used to write global snippets for your convenience.

Taking this feature a little further, I use it to create per-project notes.txt which can be used like a scratchpad for ideas.

# ~/.rake/codenotes.rake

require "etc"
require "fileutils"

desc "Create a per-repository notes file"
task :code_notes do
  user = Etc.getlogin
  notes_dir_path = "#{Dir.home(user)}/.code_notes/"
  Dir.mkdir(notes_dir_path) unless Dir.exists?(notes_dir_path)

  if Dir.exists?(".git")
    project_name = Dir.pwd.split("/").last.gsub(/\./, "")
    code_notes_dir_path = "#{notes_dir_path}/#{project_name}"
    Dir.mkdir(code_notes_dir_path) unless Dir.exists?(code_notes_dir_path)
    FileUtils.touch("#{code_notes_dir_path}/notes.txt") unless File.exists?("#{code_notes_dir_path}/notes.txt")
  end
end

The Rake task

This is the program flow:

  1. Checks if the present directory has a .git directory.
  2. If it is present, it will get the present working directory name and check if it is present inside the ~/.code_notes directory. This is where all the code notes get saved.
  3. If the folder is not present, it will create a folder and create the notes.txt file inside it.
# ~/.zshrc

chpwd() {
  rake code_notes
}

Zsh config file

The chpwd() function is a hook method provided by zsh which can run custom code whenever you cd into a directory. We just run the rake code_notes command

This solution is intended to be a quick fix and a demonstration of how zsh makes it easy to use hook methods that it provides. The code is dirty, not possibly an elegant solution but it works.