Diving into Existing Rails Apps

For me, one of the most frustrating parts of being a software developer is trying to wade into an existing project that’s unfamiliar to me. It’s particularly hard with an unknown language, platform, or toolset, but even if you know the language and platform, a new app can still present a challenge. When working with Rails apps, I’ve found a few avenues of attack that help me jump in and get productive.

1. Try the app.

Step one is always to get it running locally, log in, and have some idea what the user is trying to do. Check to see if it’s a single-page app. If it’s mostly implemented client-side in something like Ember, that’s beyond the scope of this guide.

Ok, so you have a more or less standard Rails app, and you’re trying to find the code that drives some feature you can get at in your browser. What now? Rails is opinionated enough to make the next steps concrete.

2. Run rake routes.

The table it outputs will tell you which controller and action is active. From there, you should have a decent understanding of what code is going to be running.

3. Check out the view.

Given the controller and action, you should be able to derive a view filename (app/views/controller-name/action-name.html.haml) or see a render call with a specific view.

There may be before or after filters running that were specified in a parent controller. If it seems like there’s a client-side portion of your code, do the same thing in the view: Walk up the tree by looking at your view, up to the layout it’s rendered in, and down to the partials it renders.

4. Follow the JavaScript.

If you see a JavaScript being pulled in (typically either in the head section of the HTML or at the very bottom), follow it. The JavaScript is probably either in public/javascripts (if it’s not using any sort of asset compilation, or if the compilation is taking place outside of Rails’ framework) or in application/assets/javascripts (if it is using Sprockets.) JavaScript code tends to be hard to trace because it’s callback-based and so flexible, but with some judicious logging and paying attention to the idioms you see, things shouldn’t be too bad.

Other code might be coming from a vendored Ruby gem or some random class in lib/, but everything the client sees starts as a template, and everything the server does starts from your routes. By starting from there and liberally applying grep, you should be able to get some traction.

5. Consider debugging.

I haven’t found that debuggers are especially useful with web apps. It’s often too inconvenient to have the browser time out while you’ve suspended execution. However, they do work: Pry is a good tool, and if that’s not helping, remember you can print out things by logging them with something like Rails.logger.info("my message").

6. Go for broke.

If all else fails and you still have no idea what code is running, consider just breaking everything to see what happens.