SeldomBlog

Artist. Musician. Programmer.

French Press: Bringing Meaning to the Surface

Wake up.
Stumble to the kitchen counter, rub the sleep out of your eyes. Kettle on the stove top. Bubble bubble. The sound of hot water hitting a layer of dry coffee grounds, swirling them around, lush caramel-colored head forming. Push the plunger down, slowly, strange satisfaction from such a simple task. A slow pour, dark black ringed with hues of translucent brown, fill the cup and watch the steam rise off the surface. First sip, chocolatey bitter savory delicious….

This isn’t about coffee

This isn’t about French press coffee. This is about pushing the details down and bringing meaning to the surface, like pushing down the plunger to bring the delicious mix of hot water and coffee grounds to the surface. I started thinking about this when I joined the development team at Gust. One of the things that was so attractive to me about the team was their devotion to process (XP/Agile) and expansive toolset (TDD, BDD, CI, Gitflow). One of those tools happened to include the team’s editor of choice, Vim. I had played with Vim a bit, but had always favored RubyMine for development, enamored with it’s refactoring shorcuts and language support.

As I fumbled around reaching for the escape key, forgetting which mode I was in, I felt like I was spending more time mastering Vim than the code I was working on! I missed RubyMine’s helpful shortcuts ( extract method, inline variable, intentions, oh! Intentions!). I started to consider how, in many ways, the IDE was so great because it abstracted away most of the tactical details of what you were doing ( editing textfiles ) and elevated the context and real ‘meaning’ of the intended final product ( a well-factored codebase ) to the forefont. I started analyzing everything I was doing in terms of ‘how much does this /tool\/class\/method/ push the details down and let meaning rise to the surface?’ And why should that matter? With the propagation of ever more development tools, frameworks, platforms, etc., I think it’s important that we take care not to get lost in the details, to not let our fascination with implementations take the focus away from the problems we’re attempting to solve.

Don’t Get Lost in the Details

I recently read ‘Confident Ruby’ by Avdi Grimm, in which the author talks about the ‘storyline’ of methods in Ruby, writing that well-factored methods ‘straightforwardly convey their intent’, without obstructing their storyline. Maybe that’s what got me thinking about surfacing meaning. Maybe it was the new French press coffee maker I got for Christmas. Some seeds might have been planted when watching this talk by Bret Victor, in which he suggests that we should do more to keep approaching our problems in new, and perhaps more ‘meaningful’, ways, rather than just perfecting the current de-facto techniques. In any case, it’s made me grateful for my current development team, that are putting as much effort into building domain knowledge and sharing high level context with the entire company as they are to perfecting their tooling and digging into implementations.

Drink it Up

I’ve become much more comfortable using Vim these past few months (check out Gust’s awesome Vim config for a sweet setup), and have come to find that Vim, in it’s own way, does quite a good job of bringing meaning to the surface. The different modes (insert, visual, command-line, normal, etc.) force you to consider what your intent is, and in what context you’re modifying the codebase (adding, refactoring, replacing, removing(joy!)). In the end, one of the greatest values in using both RubyMine and Vim, for me, has been the realization that the tools we use, along with the code we write, the applications we develop, the companies we run, are of the highest value when they abstract away the details and bring meaning to the surface. Think I’ll go put on a pot of Ethiopian Yirgacheffe and think about it some more…

The Master and the Student: Why Pair Programming Is Cool

I’ve taken a brief hiatus from blogging over the past few months, for which I can offer no excuse other than that I’ve had my head down working on an awesome RubyMotion app for a client (the banjo I got for Christmas may also have had something to do with it…). During this time, I’ve had the amazing opportunity to pair program, every day, with two senior developers at my current company, Cyrus Innovation - David A. Black (author of the Well-Grounded Rubyist), and Paul Infield-Harm, (Director of Product Development at Cyrus). This experience has led me to formulate some pretty strong views on the benefits of pair programming. I wanted to share a few of them in the hopes that those of you who find yourselves trying to justify pair programming to clients or co-workers, (especially pairing between devs of different skill/experience levels), can have some arguments to reference, or at the least, someone to blame!

Discussion and Knowledge Sharing

Pairing leads to a lot of top down discussion, from design to implementation, allowing the passenger to learn through questioning and the driver to refine and clarify their approach for the purpose of explaining it to the other person. When working out some timing issues with asynchronous calls in our app, Paul, David and I engaged in some group discussion and documentation digging about the various ways to call block arguments from nested block methods (yield vs. block.call). Had we been soloing, this exploration would have made one developer more knowledgeable. Instead, three developers, prodded by the challenges of the project, eachothers’ curiosity, and maybe even wanting to be the first one to find the answer, gained some valuable knowledge about how block arguments are handled in Ruby.

Confidence Building

Pairing also builds confidence for both members. For a junior like me, being given the chance to drive on a specific refactoring or debugging session can be a big boost to your nascent coding confidence. For a senior developer, being asked to explain a specific concept or design decision can reinforce his/her already solid understanding of concepts and help them to move forward without apprehension. Having the confidence to express your opinions and try to implement them is a great skill to have, and pairing can provide positive reinforcement to both partners.

Communication Skills

As a junior, one of the greatest challenges can be finding ways to explain your programming questions in an eloquent manner to people who have been doing this for years. Pairing necessitates this kind of interaction, and, as with anything else, one gets better with practice. For senior developers, getting accustomed to explaining highly technical concepts to others can be very valuable, especially in client/customer/product owner interactions, when the person you’re speaking to oftentimes lacks substantial technical know-how. In pairing with Paul and David, I was motivated to formulate my own thoughts and opinions better, which necessitated closer documentation reading and more experimentation on my own, both of which are great practice for a beginner looking to hone their skills. Likewise, I was continually impressed by Paul and David’s ability to communicate complex concepts in a clear, simple, and concise manner, the sign of true experts.

Pair!

I know there are situations where pairing might not yield these same kinds of results, though I can’t help but feel that’s a product of less than enthusiastic participants or misplaced priorities. I have the pleasure of working on a team with two consummate programmers, with whom I’ve had many productive and informative pairing sessions. For this reason, I’m extremely thankful to Paul, David, and Cyrus Innovation for the experience, and more than a little wary of anyone who dismisses pair programming as inefficient or unproductive. So give it a try, and let me know if you need someone to pair with ;)

The Power of Abstraction

‘Objects are smarter when they know less.’ Objects should know what, and trust other objects to figure out how. Nuggets of wisdom like these pepper the pages of Sandi Metz’s ‘Practical Object-Oriented Design in Ruby’. These principles are as abstract as the code they aim to inspire, and, consequentially, as powerful. In art and music, the concept that abstraction enables a greater range of interpretation and deeper meaning is widely acknowledged, but it seems perhaps counter-intuitive that this same principle would apply to code. However, as Metz states, the most important feature of well designed code is it’s ability to adapt to the changes that will inevitably come. With this in mind, it becomes easier to understand how less explicit objects can reduce dependencies and allow for a greater range of application. Let’s take a look at an example from POODR.

Duck Typing

In Chapter 5 of her book, Metz explores duck typing, or defining public interfaces (messages passed from one object to another) that are not tied to any explicit class. For me, this is an especially compelling example of the ways in which abstracting away details can make your objects more powerful. The book’s example uses a Trip object that sends the message ‘prepare’ to various other objects, including a Mechanic and a TripCoordinator.

Metz Trip Prepare Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Trip
  attr_reader :bicycles, :customers, :vehicle

  def prepare(preparers)
    preparers.each {|preparer|
      case preparer
      when Mechanic
        preparer.prepare_bicyles(bicycles)
      when TripCoordinator
        preparer.buy_food(customers)
      when Driver
        preparer.gas_up(vehicle)
        preparer.fill_water_tank(vehicle)
      end
    }
  end
end

class Mechanic
  def prepare_bicycles(bicycles)
    #prepare bicycles implementation
  end
end

class TripCoordinator
  def buy_food(customers)
    #buy food implementation
  end
end

class Driver
  def gas_up(vehicle)
    #gas up implementation
  end

  def fill_water_tank(vehicle)
    #fill water tank implementation
  end
end

In this implementation, which contains very little abstraction, there are a dangerous number of dependencies. Through it’s ‘prepare’ message, Trip knows not only which objects will receive this message (Mechanic, TripCoordinator, Driver), but how those objects prepare for a trip (prepare_bicycles, buy_food, gas_up, etc.). If in the future, we decide that there must be some other object helping to prepare for a trip (perhaps a ‘Mom’ object that packs a paper bag lunch ; ), we would need to explicitly add this class to the case statement inside ‘prepare’ and include it’s ‘pack_lunch’ method call, all in the Trip object. Furthermore, if the Driver, who’s getting quite snobby, decides it no longer will ‘gas_up’ vehicles, but ‘replenish_fuel_source_through_use_of_nozzle_guided_device’, it will break Trip’s ‘prepare’ method, which explicitly calls Driver’s ‘gas_up’ method.

Refactor

We can see that by being too tied to specific classes, we’ve made our code extremely specific and stubbornly opposed to change. Let’s take a look at Metz’s example of the above code refactored to use duck typing:

Metz Trip Prepare with Duck Typing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Trip
  attr_reader :bicycles, :customers, :vehicle

  def prepare(preparers)
    preparers.each {|preparer|
      preparer.prepare_trip(self)}
  end
end

class Mechanic
  def prepare_trip(trip)
    trip.bicycles.each {|bicycle|
      prepare_bicycles(bicycle)}
  end
end

class TripCoordinator
  def prepare_trip(trip)
    buy_food(trip.customers)
  end
end

class Driver
  def prepare_trip(trip)
    vehicle = trip.vehicle
    gas_up(vehicle)
    fill_water_tank(vehicle)
  end
end

Trip’s ‘prepare’ message, by not calling any specific classes, can now be used with any object that responds to a ‘prepare_trip’ message. If we were to add a ‘Mom’ object to pack a lunch, a ‘Chaperone’ object to watch over customers, or a ‘SpiritGuide’ object to help customers through the toughest parts of the journey, NOTHING needs to change about Trip’s ‘prepare’ message. All we have to do is ensure that all additional preparer objects have a ‘prepare_trip’ method, which will encapsulate their class specific implementation of that call (make_lunch, supervise_customers, um, guide_spirit?). By making Trip’s public interface more about what then how, we’ve reduced dependencies and made our code much more receptive to change.

CONCLUSION

By making our objects more abstract, we transform them from a Michelangelo to a Picasso, traversing centuries of artistic progress with a single keystroke. While the David is beautiful, it’s a concrete representation of a single immutable thing. Abstraction, on the other hand, allows the viewer to project their own interpetations onto a piece, allowing for an almost infinite number of meanings. In this same way, abstract code that relies more on what is happening then how it happens, and is duck typed to eliminate class dependencies, can be used in any number of ways, and fulfills the adaptability requirement of good design.

(NOTE: To anyone who finds these topics compelling, is interested in doing any sort of Object Oriented coding, or just likes reading books that make you smarter, follow the link in the first paragraph and check out Sandi Metz’s ‘Practical Object Oriented Design in Ruby’)

By Any Other Name: My 3 Favorite Ruby Method Names

‘Slice’. ‘Pop’. ‘Chunk’. ‘Squeeze’. While you might think these words were picked from a list of old comic book sound effects, (and they likely could’ve been), they’re actually just a few of Ruby’s wildly evocative method names. As a language built on expressivity and with it’s fair share of syntactic sugar, Ruby boasts a number of methods whose descriptive names act as metaphors for the sometimes abstract operations they perform. Not only does this aid in remembering methods when you need them, (hmm, I wonder which method will let me ‘pop’ that last element out of the array…), but it also turns you, the programmer, into a carpenter or sorts, manipulating and using objects in a so-close-to-real-you-can-almost-smell-the-sawdust kind of way. In this post, we’ll take a look at my three favorite Ruby method names: Tap, Inject, and Send.

Tap

When called on an object, ‘tap’ yields that object to a block where other operations can be performed on it, and then returns the object to the method chain.

Simple Use of Tap
1
cool_method = "pat".reverse.tap{|object| object << "!"}.upcase

While Ruby’s API says the method is so-named because it’s used to ‘tap into’ a method chain, for me, tap brings to mind a game of pool, where the receiver is the cue ball. Calling ‘tap’ does just that - it gives the cue ball (receiver object) a light tap, sending it to the block where operations are carried out. It’s then sent along to the next method in the chain, or in our metaphor, the next billiard ball. While I’m no pool shark, this helps me to understand the way in which tap momentarily changes the trajectory of an object in a method chain, sending it to the block for processing before it returns to the chain, like pool balls banking off a felted rail.

Inject

Inject is an enumerable method that will combine all the elements in the enum object by applying an operation specified by a block. When given a block, for each element in the enumerable, the block is passed both the accumulator value (or memo) and the element. A simple example would be using inject to sum all elements in an array.

Simple Use of Inject
1
sum = (1..5).inject{|memo, element| memo + element}

While some people prefer the similar but much less evocatively named ‘each_with_object’ method(and I might be inclined to agree with them), based on name alone, ‘inject’ is the most expressive representation of what the operation is actually doing. In essence, the block ‘injects’ the result of it’s expression into the memo each time it’s invoked, allowing for the powerful functionality of being able to act on a dynamically generated memo value.

Send

‘Send’ is used to call a method on an object in a more abstract way then simply calling the method. It takes the method being called as an argument, and any arguments for that method as additional arguments to send. When you send a method to an object, it’s as if you’re putting that method into an envelope and mailing it to the receiver. What’s powerful about ‘send’ is that the contents of that letter (the method call and arguments) can be dynamically generated.

Simple Use of Send
1
2
3
["upcase"].map do |method|
  method.send(method.to_sym)
end

There are lot’s of ways to send a message. Flowers on a doorstep. Graffiti on a wall. Dead fish in a newspaper. In all cases, sending a message is a more abstract way of telling someone what you want, similar to the way in which ‘send’ is a more dynamic and abstract way of calling a method on an object.

CONCLUSION

These are just a few of the methods whose names can paint a vivid picture of the operations they perform. Names like these can go a long way in making programmers emotionally invested in the sometimes esoteric tasks being performed. So next time you use the ‘tap’ method, don’t be alarmed if you find yourself rubbing the chalk off your fingers….

MiddleWHERE? Rack and Sinatra

In this post we’ll be discussing Rack and Sinatra, two Ruby libraries for processing HTTP requests. Though Rack is somewhat the bumbling robot to Sinatra’s martini drinking cad, they’re both very simple-yet-powerful gems for allowing your Ruby app to interact with web requests.

HTTP REQUESTS

Though most of us have been browsing the internet since we were young, the actual mechanics of how your browser grabs Justin Beiber’s latest tweet and outputs it to your screen are a complete mystery (why you would want to do this is another mystery…). In very basic terms, the browser submits a request for information, which travels through a web server and up to an application, where that request is processed and a response is sent back down the chain to the browser.

This seems simple enough, but for your application, communicating with web servers can be a complicated process. For Ruby web apps, there are numerous different web servers (Mongrel, Thin, WEBrick, etc.), all of which process the requests coming from web browsers differently, and none of which your app will inherently know what to do with.

RACK

Rack, (called middleware because it goes in the ‘middle’ of your app and a web server), aims to simplify this process. It filters and wraps the HTTP requests coming from the web server and formats them in a way that your app can understand.

A Rack application will respond to a ‘call’ method, which takes as it’s single argument a hash that contains information about the HTTP ‘request’. The call method returns an array containing the response status code (ex. 401, ouch), response headers, and response body as an array of strings:

Simple Rack App
1
2
3
4
5
6
7
8
9
10
require 'rack'

class RackApp
  def call(env)
    headers = { "Content-Type" => "text/html" }
    [200, headers, ["OK"]]
  end
end

run RackApp.new

Rack acts as a butler of sorts for your application, answering the door and translating requests into a language your app can understand. It also communicates your responses to the outside world, in this case a range of web servers with varying functionality, in a format they can ALL understand, which is pretty sweet.

SINATRA

Though it delivers some great functionality, you may have noticed Rack isn’t the suavest of communicators. Here, ol’ Blue Eyes can really smooth out the edges.

Sinatra, a DSL (domain specific language) for creating web apps in Ruby, strolls in, cigarette in hand, to abstract away messy HTTP request processing with a stupid simple syntax for interacting with Rack and Web Servers…

Simple Sinatra App
1
2
3
4
5
require 'sinatra'

get '/' do
  "OK"
end

The above code block will give us the same functionality as our Rack app, but as you can see, the syntax is much easier to understand. With Sinatra, setting up your app to handle various web requests (so far we’ve only covered ‘get’, but there are also ‘post’, ‘put’, ‘delete’ and others) is a breeze. Furthermore, for those apps that perhaps don’t need the robust functionality of Rails, it can be a great framework to get a simple web app up and running quickly and efficiently.

CONCLUSION

Sinatra and Rack Middleware allow your app to interact with the web in a clean and efficient way, letting you concentrate on building out the real functionality of your product while they take care of the dirty work.

NOTE: This post is highly indebted to an amazingly simple, funny, and informative Rack/Sinatra talk given by Tom Black. Go check it out, now.

About SQL Joins: The 3 Ring Binder Model

Any programmer worth their weight in bitcoins is going to need to know a bit about databases. If you’re not familiar with databases, you should take some time to read up on them, but hurry back, because for this post we’re going to be talking about the different kinds of JOINS. ‘Joins’ are a method of linking multiple tables in a database together so we can access values from them with a single query. Seems simple enough, but joins can be confusing. Since tables in a database aren’t tangible things, it can be difficult to understand the links we create between them. I for one find it difficult to really wrap my head around a concept until I can draw it, which made for some interesting moments in high school sex ed, but also led me to develop a method for visualizing how the different kinds of joins work! Let’s have a look:

3 RING BINDER

Picture the two tables in our database as two pieces of looseleaf. The blue lines represent our rows, or records. The dashed lines represent our columns.

Now, using the SQL syntax for sqlite3, we’ll start writing our join by stipulating which tables we’d like to link.

Writing a SELECT query using JOINS
1
2
SELECT * FROM persons
INNER JOIN orders

We’ll go over INNER JOIN in a second, but for now just picture us putting our two pieces of looseleaf into a three ring binder. We’re selecting from both persons (left table) and orders (right table), and linking them with a join.

Now that our pages (tables) are in a binder (joined), we need to stipulate which column to link them on.

Setting a join column
1
2
3
SELECT * FROM persons
INNER JOIN orders
ON persons.id = orders.pid

Here, we’re saying that we should link the rows in persons and orders based on the value of the ‘id’ column in the person table, and the ‘pid’ column in the orders table. When the values in those two columns match, we can assume a correlation between the two records.

Now we’ve joined our tables. But there are a few different ways to join two tables, which will effect which rows are returned. Let’s have a look:

Inner Join:

An inner join, or left inner join, will produce only the records for which there is a match from tablea (persons) and tableb (orders) (records produced are highlighted):

Left Outer Join:

A left outer join will produce a complete set of records for tablea (persons), with matching records from tableb (orders) when they exist. If there’s no match from tableb, the right table’s join column value will be ‘null’.

Right Outer Join:

A right outer join will produce a complete set of records for tableb (orders), with matching records from tablea (persons) when they exist. If there’s no match from tablea, the left table’s join column value will be ‘null’.

Full Outer Join:

A full outer join will produce the complete set of records from both tables. Wherever there is no match, the value will be ‘null’.

Conclusion:

Hopefully this visualization will help you wrap your head around database table joins, (and maybe conjure fond memories of decorating your Five Star™ binders…). For more on databases and visualizations for joins, you can go here, or here for some great insights.

Blocks vs. Procs vs. Lambdas: Ruby Closure Showdown

Early on in your quest to learn Ruby, you’re going to encounter ‘blocks’. These little packets of code that can be passed to methods may make you sweat a little at first, but soon enough, passing blocks to Enumerable instance methods like ‘each’ and ‘map’ will be second nature. Then, one day, you’ll encounter (gulp), a ‘proc’, or (bigger gulp), a ‘lambda’, and you’ll question why you ever got into this coding business in the first place. Luckily, you can cast those doubts aside, because despite the intimidating names, procs and lambdas are really just blocks stored as variables. Let’s take a minute to break this love triangle apart and examine the subtle differences between blocks, procs and lambdas.

Blocks

Blocks are packets of code stored between ‘do…end’ or ’{}’. They’re a way of performing an action on a value returned by a method.

Define and call a method that yields to a block
1
2
3
4
5
6
def my_method
  yield
end

my_method {"This is a block!"}
=> "This is a block!"
The example above returns “This is a block!”. The method ‘my_method’ yields to the block, which then executes it’s code.

(It actually returns ‘nil’ because of the puts statement, but we’re going to ignore that in this and future examples)

Procs

A Proc is just a block that is stored in a variable for repeated use. If we store a proc in a variable, we can pass that variable to any method that expects a proc.

Store a block in a variable as a Proc
1
2
3
4
5
6
7
8
def proc_method(a_proc)
  puts a_proc.call
end

my_proc = Proc.new{"This is a proc!"}

proc_method(my_proc)
=> "This is a proc!"
If we want to reuse the block of code stored in the my_proc variable, we can simply define another method that takes a proc and pass in my_proc.

Pass the same proc to another method
1
2
3
4
5
6
def another_proc_method(a_proc)
  puts a_proc.call + " - reused!"
end

another_proc_method(my_proc)
=> "This is a proc! -  reused!"

Lambdas

Lambdas are very similar to procs, only with a slightly different syntax.

Store a block in a variable as a Lambda
1
2
3
4
5
6
7
8
def lambda_method(a_lambda)
  puts a_lambda.call
end

my_lambda = lambda {"This is a lambda!"}

lambda_method(my_lambda)
=> "This is a lambda!"
So, lambdas are like procs. In fact, if we run my_lambda.class, we’ll see that it returns ‘Proc’ - that’s right, lambdas are instances of the Proc class. Now pick your jaw up off the floor and let’s go over the differences between the two.

Procs vs. Lambdas

Procs and lambdas behave in slightly different ways with regards to a) argument handling and b) return context. Lambdas, sticklers that they are, are very particular with arguments, and will raise an error if passed less or more arguments than were set when they were defined. Procs, on the other hand, couldn’t give two bits how many arguments you pass them - a proc will set all unused arguments to nil.

Parameter handling with procs and lambdas
1
2
3
4
5
6
7
8
9
10
11
def parameter_handling(proc_or_lambda)
  proc_or_lambda.call(1)
end

my_proc = Proc.new {|a,b| "Procs aren't sticklers about args..."}
my_lambda = lambda {|a,b| "...but Lambdas are!"}

parameter_handling(my_proc)
=> "Procs aren't sticklers about args..."
parameter_handling(my_lambda)
=> <ArgumentError: wrong number of arguments (1 for 2)>
So, if you want your reusable block to require specific amount of arguments, you should use a lambda instead of a proc.

The other way procs and lambdas differ is in return context. When a proc encounters a return statement, it will execute the proc and exit the wrapping method. On the other hand, lambdas, ever the anal retentive counterpart to the freewheeling proc, will execute the lambda and then politely continue to run the wrapping method. Let’s take a look at an example.

Return context with procs and lambdas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def return_test
  puts "beginning"
  Proc.new{return puts "middle"}.call
  puts "end"
end

return_test
=> "beginning"
   "middle"

def return_test
  puts "beginning"
  lambda {return puts "middle"}.call
  puts "end"
end

return_test
=> "beginning"
   "middle"
   "end"
As you can see, when returning our proc, we exited the wrapping method (hence the absence of an “end”), while in returning our lambda, we executed the lambda code and then continued executing the wrapping method call.

Conclusion

So procs and lambdas are really just two ways of storing blocks in variables for repeated use. Admittedly, our examples were pretty elementary, but blocks, procs and lambdas can be actually be incredibly powerful. When passed to a method call, they can act on dynamically generated variables (!), making them all ‘Closures’, which is a topic way outside the scope of this post. For now, just think of procs and lambdas as the the odd couple spawn of the all mighty block.

(Note: This post was inspired by a short and very informative presentation on the subject available on speakerdeck. Highly recommended for a more in depth look at use cases of procs and lambdas. Many thanks to the author ; )

BASH and the One True Path

As a nuby programmer, you’re going to be cozying up to your command line in ways you never before imagined. You’ll be cd’ing, ls’ing, grep’ing, and (carefully) rm -rf’ing your way around your filesystem, and, for Linux and OSX users like me, you’ll be using BASH to do it. BASH is a command processing program that reads the input you type into your command line and does things with it. You can read more about it here, and here, but the real topic of this post is the special little beast known as the PATH, so let’s get to it.

When BASH starts, it creates an environment for your shell session by executing commands from a few different scripts. These include ~/.bash_profile, ~/.bash_login, and ~/.bash_rc. Since BASH looks in your .bash_profile first, you should be setting most of your environment variables and methods there (though read up on .bash_login/.bash_rc, because they’ll be invoked under certain conditions and, reading is good for you). Let’s take a look in our bash_profile (I’m using SublimeText, hence the ‘subl’ command, but use whatever editor you’ve got):

$ cd ~
$ subl .bash_profile

What you’ll likely see (among other things we’re going to ignore in this post) is a line that reads PATH = $PATH. Those of you quicker than myself will instantly recognize that this is setting the variable named PATH. You can call that variable with $PATH (this is the syntax BASH uses, like var in Javascript). Jump back into your command line and type in $PATH. What you’ll see printed to the screen is something like this:

$ $PATH
-bash: /bin:/usr/local/bin:/usr/bin:/Users/Username/bin:

This is your PATH environment variable. It’s a list of directories that BASH will look in for commands, scripts, and programs. The filepaths to those directories are separated by ‘:’, and the directories are checked in order. So, when you type ‘git’ to access the git revision control program from your command line, BASH will first check your ~/bin directory, then your ~/usr/local/bin directory, then ~/usr/bin, and so on. As soon as BASH finds what it’s looking for (in this case, ‘git’), it’ll execute the command and stop travelling down the PATH. The PATH environment variable is like a map that BASH consults every time you tell it do something. The map says ‘Go here first, and if you don’t find what you’re looking for, go here, or else go here, etc., etc…’

Seems simple enough, and it is, but there are a few things to keep in mind.

BASH, like all programs, is pretty dumb - it only knows what you teach it. So if you want to execute a script or program from your command line, you’re going to need to make sure it’s in your $PATH, or else BASH won’t know where to look. I recently ran into an issue when trying to run Postgres.app from the command line. The documentation told me to add the /Applications/Postgres.app/Contents/MacOS/bin directory to my PATH, so I did. I was then supposed to be able to run ‘psql’ from the command line to startup Postgres, but it didn’t work. In what I would like to tell you was a very short amount of time spent running the same command and pulling my hair out, I realized that Postgres.app was still in my /Downloads directory, not in /Applications. But the directory I’d added to my PATH was supposed to be in /Applications, not /Downloads, and as mentioned, BASH will only check the directories in your PATH, and nowhere else. So I moved Postgres from my /Downloads dir to /Applications, and voila - everything worked, my blood pressure came down, and I learned a little bit about how the PATH works.

It’s also important to remember that BASH will stop looking for a program or script once it finds a match, so the sequence of directories in your PATH is important. If you have two different versions of a program saved in different places, (say, one version in /usr/bin, and one version in usr/local/bin), BASH will use the version located in the directory that appears first in your PATH. So if you think you’ve got a more recent version of a program installed, but for some reason BASH keeps loading the older version, check your PATH against the locations of your programs/scripts. You can add a directory to the front of your path by opening your bash_profile and adjusting your PATH = line like so:

PATH = “path/to/new/dir:$PATH”

And that’s the PATH. An environment variable that provides BASH with instructions on where to look for things. If you’re ever running into an issue with BASH not recognizing a command or program, check your PATH first; it may be as easy as telling BASH where to look. Now, go forth and wander.