Last Updated: February 25, 2016
·
855
· minivan

Four useful zsh aliases for rails projects

Here's a small function I use as an alias in my zhsrc:

ff () {
  find  | xargs grep "$1" -sl | view - -c "/$1/";
}

Now this is probably not the most practical of the aliases, since it goes through the whole directory tree, but it's good for small projects. For Rails, I usually use the other four:

fa () {
  find app/models app/controllers | xargs grep "$1" -sl | view - -c "/$1/";
}
fs () {
  find features/ spec/ | xargs grep "$1" -sl | view - -c "/$1/";
}
fd () {
  find db/ | xargs grep "$1" -sl | view - -c "/$1/";
}
fv () {
  find app/views/ | xargs grep "$1" -sl | view - -c "/$1/";
}

What do they do? Let's go over them step by step:

  • first we find - which shows all the files in the current directory, recursively
  • then we pipe it to xargs, which takes the output of find and line by line sends it to the next command, which in our case is
  • grep "str" - we'll be looking for string in the file which was given by xargs. Since all the files were passed line by line by xargs, we'll search for "str" in all the files, one by one
  • we'll give grep the option to display the data as a short list, (hence the -sl) in order to have just the absolute filenames
  • the result is a listing of files where "str" has been found so a next step would be to pass it to the read-only vim (view) to keep it somewhere. We append a dash at the end to make view read from stdin, which is where the pipe comes from.

So we have a view of all the files that contain "str". Now we can just go to the line that interests us and hit gf to open that file in vim.

That's it!

How will it work? Try ff somestring to look for somestring in all files, then gf to go to the file that interests you. Similarly, fa looks through the models and controllers, fs is for specs, fd is for migrations (remember when you were looking for the migration that introduced a certain change?) and fv to look in views.