Terminal Kung Fu - Tips and Tricks for the power developer
Time to power up your programming fu with this exhaustive list of tips and tricks that I’ve picked up over the last few years. In this post you’ll learn how to do what you’ve done everyday way more efficiently.
Quickly search command line history
I’m really bad at remembering commands, especially ones that have a large number of arguments. But doesn’t it get just that much more annoying when you have to sit and Google again the command that you literally used 2 HOURS ago? Fear not,
reverse-i-search to the rescue.
Open your terminal and press
Ctrl + r. Start typing the first few chars of the command that you recently used. It should start showing you commands that matches your command query. If there is more than one command that matches, press
Ctrl + r repeatedly to cycle through the commands that match your query. Press
Ctrl + e to select a particular option.
View history of the last few pages.
You can also say
history in the command line to a list of every command that you may have executed.
Reclaim hours of backspace time
Ever had this really long query that spans 4 different lines numbers on the console and now you want to go to the front or make some change.
Ever written a really long command line piece that spans 4 lines. Only to realise that you made a mistake in the beginning of the line? Now if you dont know the shortcuts, you would probably press the right arrow to go to the beginning of the line character by character. But the pros know better. They use shortcuts. These shortcuts will save you hours of time playing with the arrow and backspace keys.
Ctrl + k - Deletes everything to the right of the cursor
Ctrl + w - Deletes everything to the left of the cursor (one word at a time)
Ctrl + a - Go to the beginning of the line
Ctrl + e - Go to the end of the line
Access the last expression with _ in rails console
This is another one of those common mistakes that I make. Query an ActiveRecord model in the rails console. Forget to capture the result in a variable. Press up and then do it again this time with a variable.
Well fortunately people smarter than me also have this problem and they actually solved it.
Every time you execute an statement or function in the console, the return value is captured in a variable called
_ (yes just a plain underscore)
So this is how it works. Lets say you do this
User.first(5) in the console. You get the first 5 users but you forgot to capture that in the variable. But since you know about the
_ you can just say
_.first.name or even better you can do something like
users = _.
users variables holds the return value of
Find the Controller and Action of any URL
This one is again super useful, especially when your routes file is 500 lines long and you have 5 different namespaces and a number of custom actions.
You have a
routes.rb file that is 500 lines long and contains 5 different namespaces and number of custom routes. You have this URL and want to know which Controller and Action it hits. The obvious method would be too open the routes file and scan the entire file till you find something that hits it. You could even use something like RailsPanel to see the controller and action. But all of this takes a while.
If you want to do it in less than a second, use this command in the rails console.
Caveat: Careful when using this with non-GET actions, it will return the right controller but the wrong action.
Play in the sandbox
What to mess around with some values in the console and see how it makes your application react? But you don’t want to ruin your pristine database? Fear not, your rails console has a built in option just for this case. Instead of starting your
rails console normally start it by the command below.
rails console --sandbox
Under the rood the console starts wrapped in a database transaction. Once you exit the session, the transaction is rolled back. This way you can make add/edit/delete values but once you exit the console the database will be restored to its original state. Just be careful of running a transaction inside the sandbox as not all databases can handle nested transactions.
Reload the console on the fly
You try something in the console, it doesn’t work. You change your code and try again? Nope got to restart the console session first. Sure its fine in the beginning but it starts to be a drag after a while. You can avoid this problem most of the time by simply saying
Yup it will reload your entire Rails application without you having to terminate the session.
Caveats - This does not work inside
pry out the box. If you know how, please share it with everyone by leaving a comment.
Banish Rdoc and ri
So your surfing GitHub and come across this super awesome project. You immediately clone the repo and
bundle install. Guess what, its takes you 30 minutes to download all the gems. What makes it even worse is that half the time is spent downloading RDoc and ri files. You’ve probably never used these. Worse you probably don’t even know what they are. Suffice to say that if you have an Internet connection your not going to have to use them.
RDocs are essentially the ruby docs that come with the gems. Websites like RubyDocs use them to generate the documentation from the source code. But when you bundler it downloads it by default. So there are two ways to disable it.
The first is that if your installing a single gem use the command below.
gem install rails --no-ri --no-rdoc
This tells bundler to not download the RDoc and generate the ri files. This not only saves a lot of time but also a lot of space.
The above however works only when you install a single gem. If you want to make this the default behaviour for all the gems that you install then do this.
Step 1. Create a file called
.gemrc in your home director.
cd ~; touch .gemrc;
Step 2. edit the file by opening it in your editor of choice
subl ~/.gemrc #open the file in your preferred text editor.
Step 3. Paste the following code snippet into it.
gem: --no-ri --no-rdoc install: --no-rdoc --no-ri update: --no-rdoc --no-ri
But we can take this even further. Most medium to large projects have the gem count running into the mid 50s. This is not including dependencies of each gem introduces. For example the Discourse project has around 150 gems. Bundling this even after you disable rdoc and ri will take atleast a few minutes to install.
We can make this go even faster by running the gem installation in parallel ensuring that it makes full use of your internet bandwidth processing power. We do this by passing in the
--jobs flag into bundler.
bundle install discourse --jobs=4
Running this command you should see gems processor installing significantly faster. However does not work well at all times. There are times it goes into a deadlock or crashes. To fix this just run
bundle install discourse --jobs=1
This basically sets it back to the default state.
Peek inside of a gem
Ever wanted to look at the source code of a gem that you using? Maybe your curious or want to see how a particular function is executing. Yes, you could always google the projects github and browse there. But that means that you lose the comfort of your text editor. It doesn’t have to be this way. Just say
EDITOR=sulb bundle open devise
The editor variable in the beginning sets the command of your editor. The last thing is name of the gem. Here we are opening the popular authentication gem
devise. The advantage of this is that it opens the particular version of the gem that you are using.
You can do anything that you would do on a normal project. You can change the code to understand what it does, you can modify functions and even add functions. Once your are done seeing the code you can reset it to its orignal state by running the command
gem pristine devise
This will restore it to its orignal state reverting any changes that you may have made.
Make notes inside your source code
Often while writing code, in the heat of the moment you want to make quick note about something in the code. Maybe you want to say that you want to refactor,
Your writing code, your in the zone. You see some code that you want to refactor. The code isn’t quite right. You want to make a future note to refactor. Now normally you could switch from your text editor to your bug tracker or some other note taking program. But that comes with a mental penalty, you get out of your zone. And getting back into it takes time. What would be nice is that if you could make a note inside the code and pull at a later time.
Rails offers just such a mechanism. Anywhere in your rails application you can make a note by starting by pre-pending it with
#TODO make this a one line function. def new end
Later you can view all the notes that you made from the console by running this command.
bundle exec rake notes:todo
Now once you start to use this feature you might find that you have to too many todos. You might want something a little more descriptive. The little rake task allows you to make a custom annotation.
So you can make comments like this
#REFACTOR make this a one line function. def new end
and now when you run the rake task, pass in the name of the command that you would like to find.
bundle exec rake notes:custom ANNOTATION=REFACTOR
It will only return the tasks that have been annotated with whatever you passed in.
Find source location of any method
Often your playing with a method in the console but want to look at the source code. This is especially true for methods defined in gems that you have included. Methods often have the same name across files and your not sure which one is being called. The easist way to find the location of the source code is by running the following.
user.method(:password=).source_location => #["/Users/ror365/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activemodel-4.2.0/lib/active_model/secure_password.rb", 119]
Returns the exact file path and the line number for the file. Now that you know its an ActiveModel function you can open the gem and navigate to that exact file.
Find and describe all rake tasks
If you have a large application there is that you’ve written multiple rake tasks. Rails also comes built in with a number of rake tasks that can be hard to remmeber or find. The easiest quickest way to find rake tasks is to run
bundle exec rake -T
-T flag tells rake to lists all the rake tasks that it finds in an application. It also prints the description of the task.
Reclaim back some disk space
A co-worker of mine has a Macbook Pro with a 120Gig drive. From time to time it gets full and he goes looking for things to delete. I happened to notice him doing it once and asked him, hey have you cleared your rails logs? He said no, but then he went and looked at the log. His local development log had bloated to 2 gigabytes of space. Apparently he hand’t cleared it since he had bought the laptop.
Day in and day out developing the same application you may not realise but every request you make gets written out to a development log. While that may not seem like much, its can quickly add up. Instead of manually deleting it. You can run the rake task designed specifically for it.
bundle exec rake log:clear
This will empty your logs and you might gain some hard drive some back.
Find all outdated gems
In the open source world things move fast. And if you have a lot of gems you should update them often. However running the
bundle update command is a bit dangerous as it can break things. I recommend first running
on your project. It will give you a full list of gems that need to be updated. You can go from there and run
bundle update on individual gems.
As you know that there is no end to the number of tips and tricks one can know. Knowing these doens’t make you a better developer. Also remember that just because that someone else knows these tips and tricks they’re not better than you, though it may give the illusion of such. They’ve just spent some time googling around which you can too. These are mearly tricks to help you be a little more productive, nothing else.