The Streetlight

The streetlight stood ten feet tall, along a cobblestone path in a small, green park called Maltrova. The sun had just slipped under the horizon, taking the day with it.

Its base was bell-shaped, but had ornamental lion’s feet at the cardinal directions. The claws of each foot were extended and poised to sink into the earth.

The oxidized bronze of the streetlight was weather-worn and had trails about it from where the frequent rain ran down to the grass to form small puddles. But there were no puddles this evening. There hadn’t been rain for some weeks.

The base domed to a small bump which then gave way to the main stalk. This stem had a sinusoidal quality to the surface, which spoke to the waves crashing in the distance, just over and down the cliff face that terminated the park’s lawn.

Perched at the top of the post was a four-pane lampshade containing a giant bulb. And the bulb had just flashed on. The bulb was of an older style; it cast a warm and familiar glow, but was quite inefficient. It lasted at most a few months before its filament burnt out. The open air bottom of the shade was quite useful for frequent replacements.

Heat from the coiled coil quickly warmed the air in contact with the glass shell, and that air in turn rose to the top of the shade. There it would cool, and be displaced by newly warmed air just leaving the bulb. Convection ruled in this tiny system.

The open bottom of lampshade also gave access to insects seeking light and warmth, but had another benefit of not keeping any of the carcasses that would otherwise quickly accumulate and decrease the visual aesthetic of the streetlight. That aesthetic was the sole reason to maintain this demanding fixture in the first place.

The faint hum of its operation radiated toward the trees, but their leaves absorbed it, and it went no further. A breeze stirred and the swaying leaves speckled the ground with shadow and light.

A few airborne particulate clanked off the streetlight’s glass panes and metal stem to fall silently into the grass. Several more of these grains came down, sounding like metallic rain upon the pathway.

A flash of light in the sky suddenly outshone the lamp, whose shadow swept an arc across the lawn. The lamp’s dominance on illumination returned, and the breeze failed.

A few seconds later, a high pressure air wave met the panes in the lamp shade. The glass trembled, became a spiderweb, and then fractured into a million shards. For a fraction of a second, the ground had a terrific kaleidoscope of lightwork. But the bulb then shattered as well.

The park fell into darkness as small rocks tumbled down. Light did briefly return by way of larger, superheated stones which clattered about and dented the base of the streetlight. Sizzling boulders then collided with the lawn, throwing dirt and mulch and grass clippings into the air. They rebounded and traveled on haphazardly.

The remainder of the meteor then impacted the streetlight, and, with a screech, the metal frame gave way. The now-meteorite plowed through hedges as the lamp post lay contorted on the ground – no longer sinusoidal.

Sirens sounded in the distance as the night deepened.


The inspiration for this story struck last night while I attended my first Streetlight Manifesto concert at the Ogden Theater in Denver, Colorado.

Undreamt Networks

The Way It Is

A goal in software is to create small, reusable components. Sort of how simple, metal beams can be used to create buildings, bridges, or space stations. To take individual pieces and put them together in novel ways, to accomplish some new dream.

Electronics have grown to embrace this idea in a real way. Processors, memory, storage, and many other components are inter-connectable, and can be fashioned into anything from laptops, to satellites, to particle accelerators.

These small pieces stand alone, but are more useful when connected to other pieces. Notice the similarity to ideas? Our brains take tiny neurons which fire individually and build a sophisticated network of memories, feelings, and the amazing consciousness of which we know so little.

Who hasn’t heard that creativity is really just connecting the same dots in a different way? In the shower, you’re thinking regular thoughts, but you make a different connection between them, which results in your serendipitous revelation. You then hurry to finish showering, to make note of your idea before it fades away!

Lately, my goal with writing has shifted to building up a collection of small ideas. Ones that stand on their own, but are more useful when related to others. Turning these ideas into words, and seeing them in relation to their siblings is useful. The ideas are then clearer to me, and I can realize how they’re tied together.

The hope is to eventually build larger ideas and writings. But, in the same way that you don’t build a bridge from one piece of metal, these larger pieces are fashioned from connecting smaller ones.

Beyond

To connect metal, weld. To connect software, make a call. To connect web pages, link them. These networks of tangible or intangible entities enable us. We take one, well-designed thing and get more mileage from it when it’s connected to some other thing.

Our brain connects billions of nerve cells into a network of staggering capability. But this only works within a single organism. What about linking organisms together?

We’ve invented (or discovered; we may never know) speech, oral traditions, writing, books, music, radio, film, video games, and photography. These are all meant to communicate ideas from one person to another. They’re a means to connect the neuron that is me to the neuron that is you. And our culture and civilizations have exploded with the force multiplied through these connections.

But computers fail. People pass away. Books and photos burn. Memories and radio transmissions fade. Knowledge is lost and rediscovered. But that’s only the way it’s been, not the way it has to be.

To step beyond our current position, we must invent (or discover) how to better connect people; how to store our knowledge in small pieces we can link in elaborate and impressive ways.

What’s the next step beyond books, colleges, the Internet, and all other traditional forms of sharing knowledge?

How do we connect humans to one another, to the living world, to beyond? How do we join all these neurons and power the consciousness that arises from that network?

It lies in learning to remix what is now in new and not-yet-obvious ways.

The only way we’ve found to get anywhere is to leave something behind. (Thanks, Interstellar!) Let’s leave behind our fragile books and lone consciousness as we propel future generations on toward that new, distant shore.

How do we begin? Experiment.

What The Weekend Brings

It’s now Saturday, and I’m hit with two conflicting thoughts.

The first is:

It’s the weekend, so now I can work on my side projects!

This is appealing because I have all today and tomorrow in which to make progress toward my goals of software, writing, or drawing. I don’t have this much free time available during the week, so it makes sense to capitalize on it.

The second thought is:

It’s the weekend, so now I can watch a TV show, take a nap, hang out with friends, or read!

This is appealing because I’ve worked throughout the week, and now is the perfect time to do something away from the computer. It’s important to recharge to avoid burnout.

I say they’re conflicting thoughts because one involves working on projects, and the other means taking a break from projects.

What to Do?

But, when framed this way, these thoughts lead me to believe I’ll either spend the entire day doing one thing, or the other.

Realistically, I should be able to do a bit of both. On a weekend day, where I’m setting the schedule, there is enough time to write for a while, watch some Netflix, and then also hang out with friends.

It’s one thing to realize there’s a chance for balance, but it’s another thing entirely to know and feel it.

It’s curious I think this way, and I’m not entirely sure why I do. I believe my father has this tendency, so maybe it rubbed off? That, or time during week nights is in limited supply, so it usually is one thing or the other. And since there are more week nights than weekend days, the one-or-the-other mentality is my normal one, which carries over to the weekend, even when it isn’t applicable.

Deciding

What can easily happen, though, is that I waffle over what I should do. Do I work on everything-wordpress to add image uploading, or a blog post like this, or the Fourth Mechanism (part of the Mechanism Collection), or another story that’s brewing in my mind, or my one minute timer application, or something else entirely?

It’s difficult to settle on one idea when there are so many competing for attention, and each are worthwhile.

So what, then? I’ll probably just piddle my time away on distractions, or flit between multiple things, without actually focusing very well on anything

Break It Up

Perhaps this really means I’m not good at segmenting my time? I don’t regularly give myself 1 hour for this, 2 hours for that, 30 minutes for the other. But on the weekend, should I really even have that mindset? Especially if it’s leisure time?

If I really want to get multiple things done, I suppose some amount of managing time in the day is still necessary.

Just Pick Something Already

Today, I took the approach of doing what struck my fancy. I read while walking on the treadmill for an hour, and then I wrote (part of which turned into this post), and then I worked on some code.

There are other ways to decide what to do, but a reliable method is to just go with the flow and do what interests you in the moment.

Marketdown: Exploring DCI

I recently read a book titled Clean Ruby by Jim Gay. It wasn’t too long, but I found the content quite interesting.

In it, he describes a way to write cleaner Ruby code using the Data-Context-Interaction (DCI) pattern.

Thin Controller; Fat Model

In a typical Rails app, which ascribes to “Thin Controller; Fat Model”, each model has many responsibilities. Instead of having one enormous model file, we can group related methods or behavior, and extract them into modules/concerns. We then include them on the model.

The downside of this approach is that every instance of that model class has every one of these methods on them, all of the time. Regardless of what controller action was invoked, each instance has all these methods, most of which are likely not used during this single action.

Service Objects

To slim down our models, one option is to use service objects. This is an approach I like. You can break your code into smaller pieces based on responsibility and use patterns like decorators, presenters, observers, and others. Data-Context-Interaction seems like an extension of service objects.

Explaining DCI

The “service” in this case is really the Context. The context is the thing we’re trying to accomplish. If we’re purchasing a book, then the context is Purchasing.

A context may have one or more objects, the Data, which interact to accomplish some task. The data play “roles” in this context. To purchase a book, we can imagine two roles: Purchaser and Book.

The interaction between the data in this context is what glues things together. Here, that interaction could be complete_purchase.

Gems for DCI

Jim created the Surrounded and Surrounded-Rails gems to allow us to use DCI in our Ruby/Rails applications.

Note: I did have issues where the surrounded-rails didn’t seem to do what it promised by automatically include Surrounded in the models.

My Demo

Since I’ve been interested in writings and markdown lately, I decided to create a small Rails 4 app which would allow people to sign in and create a book, which other people could then purchase.

I called it Marketdown. You can view the live demo as well as the code.

You can test out the demo yourself:

  • Type in a username, and sign in
    • No passwords here, it’s really barebones
  • Create a book yourself
    • You can entire Markdown, which will then be rendered as HTML when people view your book
    • HTML should be escaped, to hopefully prevent some maliciousness
  • Purchase a book someone else has created
    • Don’t worry, there’s no credit cards or anything.

Once you purchase a book, the site indicates that.

That’s about the extent of this demo.

Digging In

The most interesting part of the demo is how purchasing a book is handled. The context, as we mentioned above, is Purchasing.

In the site, we have users. And a user who wants to purchase a book plays the purchaser role. The book they’re purchasing, no surprise, plays the book role.

The benefit of roles is that a generic class like User can be used, but given a more meaningful name in this context, based on the role.

We “trigger” the interaction between these two roles with a method called #complete_purchase.

The trigger contains the business logic behind purchasing.

  • A user has to be logged in
  • An author can’t purchase their own book
  • A user can’t purchase the same book twice

The context is where this business logic lives. It doesn’t have to be stuck in the controller, on in the model. The controller just invokes the context.

Another huge advantage of DCI and the Surrounded gem is that we can add behavior to each role, only in this context. The methods are added to the role’s instance, scoped to this context. The instance starts playing the role, so it gains some additional behavior. When the instance is done playing the role, it loses the behavior.

This seems like a great way to limit behavior to specific instances, to help keep your models clean. You only add behavior to instances just when you need it. Your models retain their persistence, validation, and other ActiveRecord magic all the time, but they receive additional behavior based on the roles they play.

When a user is signing up, neither the User class nor the user instance need the #owns_book? method. They’re outside the Purchasing context, so they don’t have it.

In another context, Authoring, an author can #publish_book, because they need that behavior. But outside this context, the user doesn’t need that ability.

Discussion

After talking with my coworker, Zac, about this pattern, there is a downside to DCI.

We’re used to creating classes, which give behavior to instances of that class. It’s standard OO. But it would be surprising for someone to look at the above demo, without understanding the concept behind DCI, and understand what’s going on. It violates the principle of least astonishment.

Perhaps it’s just that this pattern is new and unfamiliar. With a bit of communication and understanding what problems it solves, that could become clearer.

But it is another abstraction we’ve added to our design and mental model of the software. Perhaps the ideas are worthwhile, but is the cognitive overhead of the pattern more valuable than the cost to learn, understand, and apply it? Zac gave several links which had interesting discussion about abstraction.

Concluding

I’ve only just become aware of the DCI pattern, and Marketdown is my first foray into applying it. I’ve not had any production experience with it. It does pique my interest though.

I like the concept of breaking an application’s features into contexts, which isolate behavior to their roles, and allow them to interact to accomplish something larger.

I would like to see what the software’s design looks like when DCI is applied to real problems on a larger scale. I’ll keep an eye our for other projects that might use this. And I’ll see if I can apply it to a future side project of mine.

Writing this post alone has helped me better understand the concepts, and I hope it’s useful to someone else. Thanks for reading!

Using Before Blocks In RSpec

RSpec is a handy tool for writing tests in Ruby. Writing tests means constantly learning. It takes a long time to learn what to test, how to test, and how not to bite yourself in the ass later. And even then, you’ll learn more as you write your next set of tests.

The latest tests I’ve worked with are controller specs, to assert the behavior and output from Rails controller actions.

They have evolved to look something like:

Note: The code blocks below have some pseudocode. I want to convey my meaning here, rather than give 100% working code.

require 'spec_helper'

describe SomethingsController do
  describe 'GET index' do
    describe 'with an existing something' do
      let!(:something) { FactoryGirl.create :something }
      let(:action)     { get :index }

      # This is what we're interested in, for this post.
      before do
        action
      end

      it 'returns okay' do
        expect(actual_status).to eq expected_status
      end

      it 'has the right output' do
        expect(actual_output).to eq expected_output
      end
    end
  end
end

The topic of this post is the before block. It calls the action before each it block runs.

This helps reduce duplication across assertions, particularly when there are many. It also ensures we run the action for each assertion. It can be easy to overlook a missing action call.

But, there is a downside to this pattern. I believe RSpec runs before blocks as they are encountered. This means that, if you include shared examples, which may include other contexts and other shared examples, then your tests might not run as you expect.

Consider if we now want to authorize an API token given with the request. Since we want to do this across many controllers, we can include contexts and shared examples to ensure this same behavior in many areas.

require 'spec_helper'

describe SomethingsController do
  describe 'GET index' do
    describe 'with an existing something'
      # NEW!
      include_context 'with API token'

      let!(:something) { FactoryGirl.create :something }
      let(:action)     { get :index }

      before do
        action
      end

      # NEW!
      include_examples 'authorize API token'

      it 'returns okay' do
        expect{actual_status}.to eq expected_status
      end

      it 'has the right output' do
        expect{actual_output}.to eq expected_output
      end
    end
  end
end

The shared example would look something like:

shared_examples 'authorize API token' do
  describe 'with no API token' do
    before do
      remove_header :api_token
    end

    it 'returns unauthorized status' do
      expect(actual_status).to eq unauthorized_status_code
    end
  end

  describe 'with invalid API token' do
    before do
      set_header :api_token, 'AnInvalidApiTokenHere'
    end

    it 'returns unauthorized status' do
      expect(actual_status).to eq unauthorized_status_code
    end
  end
end

Now, when we run the specs, we get a failure. The actual_status is 200 instead of the 401 we expect. Why is this?

In the shared examples, we modify the request’s headers, right? But we didn’t modify the action like we expected to. The action already ran, thanks to that before block in the controller spec. So the action used the regular, valid headers, because the contexts in which we modify the headers were included after the action had run.

We didn’t modify the action/request before it ran, like we wanted. So we didn’t get the status we expected.

But we can fix this issue. The solution is to yank the before { action } piece, and call the action in each it block. This way we can modify contexts as we need, and only run the action right before we check the assertion. This is really what we want.

The controller specs, updated as described above, would look something like:

require 'spec_helper'

describe SomethingsController do
  describe 'GET index' do
    describe 'with an existing something'
      include_context 'with API token'

      let!(:something) { FactoryGirl.create :something }
      let(:action)     { get :index }

      # We removed the before block with the action...

      include_examples 'authorize API token'

      it 'returns okay' do
        #NEW!
        action
        expect{actual_status}.to eq expected_status
      end

      it 'has the right output' do
        #NEW!
        action
        expect{actual_output}.to eq expected_output
      end
    end
  end
end

And here are the shared examples:

shared_examples 'authorize API token' do
  describe 'with no API token' do
    before do
      remove_header :api_token
    end

    it 'returns unauthorized status' do
      # NEW!
      action
      expect(actual_status).to eq unauthorized_status_code
    end
  end

  describe 'with invalid API token' do
    before do
      set_header :api_token, 'AnInvalidApiTokenHere'
    end

    it 'returns unauthorized status' do
      # NEW!
      action
      expect(actual_status).to eq unauthorized_status_code
    end
  end
end

We must remember to manually call the action for each assertion, but we gain the benefit of greater flexibility. This is important for the tests we write now, and also those we’ll write in the future.

Oh yeah, since we kept things simple and reduced astonishment, our specs run like we expect them to. Now our tests are back to green!

Manually Update Postgres Timestamps In Rails

Let’s say I need to set a boolean field on 100,000 records at the same time. And I’m using Rails 4.x, just to clarify.

The simple way to do this is

unprocessed_records.each do |unprocessed_record|
  unprocessed_record.processed = true
  unprocessed_record.save!
end

But this results in 100,000 ActiveRecord objects instantiated and held in memory at the same time. Since all I’m doing is updating an attribute, this is not efficient in memory or time.

A more efficient way to update all these records at once is #update_all.

unprocessed_records.update_all(processed: true)

The benefit is that it doesn’t create an ActiveRecord instance per database record. It also skips validations and callbacks from the model, so the database update is faster.

One thing ActiveRecord does give us is the timestamps. Each time we #save a record, its updated_at is modified. Using #update_all, we lose that. In the case of a database migration, we might not want the timestamps updated, but, in this use case, we certainly do.

Additionally, #update_all inserts values into the database without passing them through ActiveRecord’s typecasting. So it’s important to use the correct value, since ActiveRecord won’t do anything magical for us.

So how can we use #update_all and still ensure the timestamps are kept current?

In searching, I came across this StackOverflow question from 2013. The accepted answer mentions that you can pass #update_all a value of updated_at equal to DateTime.now. But I wanted to be sure this solution would still work today.

In the Rails console, I found the value which would be put into the database.

> DateTime.now.to_s
=> "2015-04-27T18:20:28-06:00"

Next, I had to check whether this value could be used for our column type, since ActiveRecord won’t be typecasting it.

My database is Postgres, and for created_at and updated_at we use the column type timestamp [without time zone].

The output in the Rails console above clearly has the timezone information, so I needed to check whether that’s acceptable for Postgres or I’d have to munge the value.

Postgres’ documentation on date/time types has the following:

Note: The SQL standard requires that writing just timestamp be equivalent to timestamp without time zone, and PostgreSQL honors that behavior. timestamptz is accepted as an abbreviation for timestamp with time zone; this is a PostgreSQL extension.

This lead me to think I could use the value of DateTime.now.to_s and be fine. I tested it out from the command line, and verified it worked. The timestamp had the correct value.


So, when you need to manually update timestamps in Postgres using Rails, use DateTime.now.to_s.

Keep this in mind when you need to update many records along with their timestamps. We don’t get all of Rails’ magic, but it will save the server a lot of time and memory.


Update: My co-worker Zac McCormick asked a good question. If we need to store the time as UTC, does Postgres convert non-UTC times to UTC time before it strips the timezone?

The answer appears to be no. This SO answer tells us timestamp [without time zone ignores a timezone modifier if we should add one. The time zone is assumed to be that of the time zone setting.

If your server’s timezome is not set to UTC, and you want to store UTC timestamps, you’ll have to convert the time yourself. This other SO question has a good answer.

DateTime.now.to_s => “2015-04-27T19:07:55-06:00″ DateTime.now.new_offset(Rational(0,24)).to_s => “2015-04-28T01:07:56+00:00″

Question Everything

What is vitally important in every person’s life? Understanding why you do what you do.

From the time we’re born and all through childhood, our parents tell us what to do – when, why, how. We trust them. We trust that what they tell us is in our best interest. It’s an evolutionary advantage for us as children, since we don’t know enough to make wise decisions, particularly ones that keep us alive. We have faith in our parents that what they say is correct, and we don’t question them. They’re the experts we rely on to stay alive.

Even when we enter adulthood, we still learn from our parents and others. But we should exercise caution with the blind faith we place in people. As we grow older, we must ween ourselves off of trusting that others know what’s better for us than we do.

We live in an age of experts. From doctors and dentists, to car mechanics and financial advisers, to politicians and religious leaders. We’re taught to trust what experts say, without question, because they know best. At least in their subject matter. But people are fallible. People have fears, biases, weaknesses, power trips, sleepless nights, motivations, ignorance, forgetfulness, lack of experience, and the way they’ve always done it.

At a certain age, we should question the validity, truthfulness, and applicability of what others say. If it’s in your best interest, there should be a good explanation and reason why. Beware anyone who tells you to do something “because I said so” or “just trust me”. Don’t be the gullible person taken for all their worth.

Many experts we’ll meet are experts of a particular field; they’ve made a career of it. But they’re just people. They have, just like you and I do, all the limits of the human condition. So they’re not all-knowing and well-intentioned.

How about the fact that any professional whom you pay has an opportunity to and a certain advantage to get you to pay them more money. This, combined with all the other human limitations they face, should be a red flag to question whether the repairs the mechanic has quoted you are really necessary. Same for when doctors prescribe medications or refer you to a specialist or say you need some procedure.

This isn’t to say “never trust anyone”. But, rather, be quite careful about who you trust. If they are truly experts, they will have sound reasoning and experience behind their advice. So hold them accountable.

Make them justify their comments, explanations, commands, recommendations. If they don’t make sense to you, push back. Ask them to explain it again, in a different way. Make them clarify their viewpoint. A true expert should be able to do this. Ultimately, you’re the one who makes the decision, so make sure you’re well informed.

There are areas of which we’ll have no knowledge or experience or interest. But require that the experts who do back up their statements with reason, logic, and an ability to explain it to the average Joe. Otherwise, how could we call them experts?

And if we should require this effort of experts, how much more should we require it of people in general?

It’s easy to set our autopilot and go with the flow, but we should still be conscientious of our actions. There’s a power in understanding the why behind an action.

Don’t just do what you’re told. Question everything and everyone. Challenge them. Make them make sense to you. When you act, be sure you’re the one who’s deciding. That way, you hold the power in your life.

Password Protecting A Zip File on OS X

Every once in a while, I need to zip up some files, so I can send them to someone else, and I want to password protect the zip file.

I’m not actually sure how to do that with a GUI client on OS X. So I use the command line to create a zip file with a password.

I do it infrequently enough that I have to look it up each time. I wanted to leave my future self a little note on how to do this again later.


Zipping A File

To zip up a file and have that be password protected:

$ zip -e your_archive_name.zip the_file_youre_zipping.txt

Zipping A Folder

To zip up an entire folder and have that be password protected:

$ zip -er your_archive_name.zip the_folder_youre_zipping

Entering The Password

For each of the above commands, you’ll be prompted twice to enter your password.

Note: I believe there is a 32 character limit for passwords when using zip.


Choosing a Password

How do I choose a password for this file?

I want it to be long, so it couldn’t be brute forced, but I want it to be easy to type too.

If I email the zip file to someone, I’ll send the password out-of-band, so I want the password to be easy for them to type. Long, complicated passwords can be a pain in the ass to type.

“Oh, you messed up one character, and you don’t know where, so you have to type them all in again.”

The person typing in that password would hate me for choosing it. So I use a passphrase, assembled from a list of random words.

To get a list of random words, I use an online random word generator.

I can use the 8 random words on that page to come up with a 32 character password. One that’s easy for the person to type, but long enough to not be randomly guessed.


There you go, future-Kyle. I hope this helps you out.

PS. Thanks to this article for teaching me how to do this.

Taking Screenshots of Webpages

It can be handy to take screenshots of your entire web page. But pages are usually longer than our sceens are. This means it’s not feasible to use the regular keyboard shortcuts for taking screenshots.

Fortunately, there are a couple methods we can use!

Take a Full-Page Screenshot

In Chrome

You can use the Full Page Screen Capture Chrome extension to capture the entire page page right within Chrome.

The benefit is Chrome itself is rendering the page.

Resize the window to be the width you want, and then use the toolbar icon to start the snapshot.

It’ll give you an image you can use by saving or copy-and-pasting.

Using a Desktop App

Paparazzi! is a standalone application for OS X that can take screenshots of the entire page.

It uses WebKit, so the rendering should be similar to Chrome/Safari.

It has some features like being able to default the size of the rendered page to that of a MacBook Air, or other screen resolutions.


These are the methods I’ve used so far to take screenshots of entire pages, but I’ll update this if I come across others.

Taking Screenshots on OS X

There are several ways to take screenshots on OS X.

Some are covered in an Apple support article, but I’m never going to remember that page. So I’m going to make some notes here.

I’m a fan of keyboard shortcuts, so I’ll emphasize those.

You can capture the entire screen, a window, or use your mouse to select an area.

If you save a file, it will be saved to your desktop by default.


Save Screenshot of Entire Screen

To a File

Shift+Cmd+3

To Clipboard

Shift+Cmd+Ctrl+3


Save Screenshot of a Window

To a File

Shift+Cmd+4, Space, then use your mouse to hover over the window you’re interested in.

To Clipboard

Shift+Cmd+Ctrl+4, Space, then use your mouse to hover over the window you’re interested in.


Save Screenshot of a Portion of your Screen

To a File

Shift+Cmd+4, then use use the crosshairs to drag and select the portion of the screen you’re interested in.

To Clipboard

Shift+Cmd+Ctrl+4, then use use the crosshairs to drag and select the portion of the screen you’re interested in.


Clipboard vs Files

Capturing the screenshot to the clipboard instead of a file can make it faster and easier to use. You can paste the screenshot in your clipboard to Slack, GitHub, Messages and use it right away. No need to use the upload file dialog or drag and drop the screenshot.

Extending Screenshots

You can use apps like Dropbox or CloudApp to tweak your screenshot workflow.

Dropbox can save the screenshots to a Screenshots folder, instead of the desktop. And then it puts a shareable link into your clipboard. This can make it fast to share with someone else.

CloudApp can do something similar.