Master Sword
<%= 'Cause it's late and your mama don't know %>
Sword

Good Listens: Podcasts

I’m not the biggest fan of air travel; if I want to go somewhere, I teleport drive, no matter the distance. (I know the statistics, friends.) To this point, my farthest sojourn destination has been Austin, TX—some 1,400 miles and 20+ hours (by highway) from Pittsburgh. In addition to enjoying my first Airbnb stay in Memphis, TN, I had the chance to reaffirm my belief that being alone with brain-stimulating audio is a real treat.

Walking in Memphis, TN.

On the first leg of my trip—an overnight migration from Pennsylvania to Tennessee—I listened to Andy Weir’s The Martian in its entirety. (It deserves better, I know; but hey, it got me through the night.) When the driving resumed, I turned first to Spotify (a nice bit of padding, as it were) and then to my favorite podcasts. It was during this stretch of pedal pushing (or, more appropriately, cruise controlling) that I decided it was high time I document some of my favorite podcasts. Alas, here are 10 podcasts (in no particular order) that I’ve come to appreciate to varying degrees (and for varying reasons) over the last few years.

1. This Week in Startups

Jason Calacanis hosts founders, investors, tech journalists, etc. in keenly improvised one-on-one interviews and roundtable discussions of tech/startup news. Almost 600 episodes in, Calacanis and team have crafted a source of information wealth that delivers week in and week out.

Good Episode: TWiSt #46 with DHH

2. The Ruby Rogues

Charles Max Wood hosts a panel of rogues for weekly discussions on programming, people, and the ever-important intersection points. If Ruby is or has been your language of choice, you’ve probably listened to an episode or two. The panel has seen plenty of change, but it has remained informed and insightful throughout.

Good Episode: RR Game Development with Andrea Magnorsky

3. Foundation

Kevin Rose sits down with founders for deep-dive interviews that showcase the stepping stones of each founder’s past. What Foundation lacks in episode count it makes up for in production value. Rose’s conversational interview style and the show’s homey settings make this podcast a warm cup of tea fit to remedy an uninspired evening.

Good Episode: Leah Busque of TaskRabbit

4. Serial

Beginning last October (2014), a podcast called Serial captivated the world. The first season examines the 1999 disappearance of Baltimore high-school senior, Hae Min Lee, and the eventual murder conviction of her ex-boyfriend, Adnan Syed. Just this month, the case was reopened by a Maryland judge. A second season (with a new case) is forthcoming.

Good Episode: Episode 01 – The Alibi

5. The Tim Ferriss Show

Tim Ferriss breaks down the art and science of learning in interviews with world-class performers of all types. Ferriss combines calculated questioning and fluid conversation to reveal practical tips and philosophies for listeners.

Good Episode: Episode 61: Matt Mullenweg

6. Mystery Show

Gimlet Media is making some great podcasts, and thus far, my favorite has to be Starlee Kine’s Mystery Show. The podcast features Kine as a detective tasked with solving mysteries with resolutions beyond the grasp of Google’s index. The episode linked below tells one of the best stories I’ve heard; if you listen to just one of the good episodes I’ve referenced, I encourage you to make it this one.

Good Episode: Case #3: Belt Buckle

7. StartUp

Another Gimlet Media production, StartUp follows the equal-parts exciting and terrifying adventure of starting a company. I haven’t listened to the introspective first season; but the second season, which follows Y Combinator startup Dating Ring on their quest to disrupt the online dating space, was quite good.

Good Episode: S2 Episode 4: Save the Date

8. JavaScript Jabber

Like The Ruby Rogues, JavaScript Jabber features an array of panelists and a subject matter expert (or two) each week. JSJ centers its discussion primarily around front-end technologies, and its panel does a great job of extracting bits of information for developers of all levels.

Good Episode: JSJ GraphQL & Relay with Nick Schrock & Joe Savona

9. Internet History Podcast

Internet History Podcast, hosted by Brian McCullough, deserves its endorsement by @StartupLJackson. If you’ve heard of terms like “the browser wars” or “the information superhighway”… If you know Marc Andreessen only as a Twitter celebrity and VC… If you hold firm that Al Gore invented the Internet…this podcast could be for you. Seriously, though, it’s quite well done; just five episodes in, I’ve had a lot of fun listening to McCullough’s detailed summaries of the events surrounding the advent of the web browser.

Good Episode: Chapter 1, Part 1 – Mosaic

10. Reply All

Rounding out my list is Reply All, “a show about the Internet,” hosted by PJ Vogt and Alex Goldman of Gimlet Media. Reply All can range in mood from appropriately playful to admirably serious, and the subject matter is less constrained by the Internet than it is extended by it. Reply All is like a box of chocolates; sometimes you get LSD.

Good Episode: Episode 30: The Man in the FBI Hat

~

I’ll close by mentioning that Stitcher is my go-to app for podcasts. If you have any podcast recommendations, I’d love to hear them.

“Only” is Lonely: On Ruby Rogues 198

On Thursday evening, the tweet stream brought me this:

Undoubtedly, I have certain expecations when spending a 40-minute commute with the Ruby Rogues. I will learn about someone doing something that probably impacts some other people in some awesome way. I think we can agree upon the common theme, there. However, when it came time to tune in to Episode 198: Expanding the Ruby Community Values to Other Languages, I found my expecations a bit different; I had a context, and it was there to stay.

Let me first say that I have great respect for each of the Rogues—current and former. I thought both Jessica and Coraline (the two Rogues on the episode) did a tremendous job of tempering the discussion when observations became less about fact and more about limited perspective. The aim of this post is not to attack the podcast or its participants, but to offer some thoughts on awareness, perspective, and the importance of synergizing these qualities when trying to affect positive change in community values.

Also, to be clear, I found the episode informative, and there were certainly sentiments with which I agree. The impetus for this post comes from the opening discussion about Ruby Community values.

MINASWAN

Matz is nice, and so we are nice.” I heard this oft-mentioned Ruby maxim for the first time at Steel City Ruby 2014. It sticks with you. It serves as a nice reminder—because we all need reminders from time to time—that we can and do impact the happiness of those working and learning around us. The stickers are pretty cool, too.

MINASWAN—the acronym—was born of Ruby, and having an acronym for describing a cultural ideology can certainly aid in the spreading of said ideology to other communities; but that doesn’t mean that other established or nascent communities fail to embody the associated qualities. The year is 2015; MINASWAN is bigger than Ruby. And this is not to say that Rubyists should purvey relevant ways of thinking less frequently. We should be aware, however, that using the phrase “only community” when speaking about these things is both misinformed and self-alienating.

Awareness of Perspective

Perspective is everything. (You know, “the dress.”) A shift in perspective can change your world. It is important, therefore, to be aware of your perspective as it relates to others’. Operating with an append-only perspective can be a dangerous game, especially when a kind of selection bias plays the part of pushing ideas onto the stack. This leads to unfounded claims, and if your goal is to bring values from one community to another, understanding the dynamics of both communities is a good place to start.

Ultimately, communities aren’t about programming languages; they’re about people. Behind every value dear to the Ruby community stands a collection of individuals who live and work with these values close to heart. Expanding values from one community to the next isn’t about transplanting ideologies; it’s about cross-pollination and perspective exchange. The common thread is people, and we can all learn from one another. The best teacher is also a student.

~

“Only” is an adjective that one uses to distinguish one thing from the others. It doesn’t do us a lot of good when proliferating values is the goal at hand. It sets us apart in a way that lacks perspective and is—in some cases—untrue. It is, in fact, detrimental to the mission. That’s not what we want.

P.S. Snickering at the prospect of writing PHP for a living (when you’ve had very little to no experience with the language) is just so stupid. I hate that more than most things.

Event Selectors, Data Objects, and akt.js

When developing web applications without an organized approach to writing JavaScript, you can quickly end up with quite the mess. Inlining script tags in HTML partials may seem innocent enough—especially when a project is in its infancy. However, a few click handlers here and a dash of data-binding there can spiral out-of-control in a hurry. The appeal of inlining server-rendered arguments in function invocations becomes an afterthought. The behavioral component of your application becomes exceedingly brittle, and each subsequent change becomes a new turn in a frustrating game of Jenga.

...
<button class="btn">Go!</button>
<script>
  jQuery('.btn').on('click', function(e) {
    alert('Go!'); 
  });
</script>
...

Here are a few weaknesses to this approach:

  1. Increased likelihood of global scope pollution
  2. Scattered and incoherent code
  3. Blocking inline scripts

A separate concern is the common usage of class- and id-based selectors for wrapping DOM elements in jQuery objects. While there are certainly performance considerations to be made when stepping away from this practice, it is worth thinking about selection in terms of separating concerns. In the code snippet above, the btn class is probably serving multiple purposes: we use it as a CSS selector to apply styles and as a DOM element selector to bind an event handler. This type of coupling should trouble us. If at some point we decide to apply the styles associated with the flat-btn class—switching out the class name—we effectively break the behavior associated with the .btn selector.

Event Selectors & Data Objects

I’ve found that using a separate “event selector” can be a great way to isolate responsibility and convey behavioral meaning. This is essentially just a specific data attribute with intention-revealing values used throughout the application. We can of course use the data attribute and its value as a DOM element selector, much like we would use a class or id.

<button data-event-selector="btn-trigger-go">Go!</button>

...

function $(selector) {
  return jQuery('[data-event-selector="' + selector + '"]');
}

var $btn = $('btn-trigger-go'); 

Also, in the absence of view models (a la Knockout or Angular), it helps to have a painless way to pass data around the application. Rather than creating separate data attributes for each piece of information we need to process, we can make use of something like Michael Best’s JavaScript Object Literal Parser to parse all data from a single “data object” attribute.

<button data-event-selector="btn-trigger-go"
        data-data-object="name: 'Gatsby', teams: 2">Go!</button>

...

var data = parseObjectLiteral($('btn-trigger-go').
           data('eventSelector'));

akt.js

I bundled these two concepts—event selectors and data objects—into a small JavaScript library called akt.js. The README describes things fairly succinctly. Enjoy.

I Lost a Friend Today

I lost a friend today.

I lost a welcoming committee with one dedicated member. I lost a subtle heartbeat in an otherwise silent room. I lost a precious face, an eager smile, and a warm presence. I lost a knee-buckling stare and a grin-inducing yawn. I lost a companion eater, drinker, and dreamer. I lost photogenic perfection—the life behind a two-year desktop background. I lost white light in the dark of night. I lost a family member.

A dear friend.

All of this and so much more; I lost a friend today.

A Simple Router on Rack

This past weekend, I found myself playing around with Rack—a “a minimal interface between webservers supporting Ruby and Ruby frameworks.” Rack is—as you may know—one of the integral interfaces implemented in Rails. The config.ru file in the root of every Rails application is commonplace in Rack applications. You consult this file each time you start the Rails server, and you can use it to insert middlewares into your stack.

While the “writing a lightweight Rack framework” exercise foreshadows another accidental, not-so-capable Sinatra, it can be fun and informative to experiment. Plus, when you’re in a rush to get the website up for next summer’s frozen banana stand, your most efficient route is most certainly framework development. And so I began.

Rack in Action

My progress thus far isn’t extraordinary, but I’m happy to have had the pleasure of deploying something non-Rails on Heroku. (Heroku has a nice guide on deploying a Rack application.) Progress aside, though, I’d like to focus on two facets of the router implementation: block-style configuration and mapping/decorating requests.

Adding Routes

Let’s begin with block-style configuration: This is a fairly common pattern. You’ve seen it in various Ruby gems and—yes—in routes.rb. Some might call it sexy. I’ll call it “Ruby and its wonderful DSL-building features.” The bulk of my implementation is below.

class Router
  class << self
    attr_accessor :routes
  end

  def self.routes
    @routes ||= Routes.new
  end

  def self.load
    yield(routes)
  end

  ...

  class Routes < Hash
    def add(verb, path, mapping)
      rkey = "#{verb}##{path}"
      self[rkey] = mapping
    end
  end
end

First, we access the eigenclass of Router and define a reader/writer. This allows us to access the @routes class-level instance variable (initialized just below) directly from class methods. In this case, we define a Routes class that inherits from Ruby’s Hash and implements a single instance method—Routes#add. This method will be responsible for mapping keys (created by the unique combination of an HTTP verb and a URL path) to controller mappings (e.g., users#show). We define self.routes to be a new instance of our Routes class. Lastly, we include a self.load method, wherein we yield self.routes to a block.

Let’s see the Router class at work and define some routes.

Router.load do |routes|
  routes.add "get", "/", "pages#index"
  routes.add "get", "/users", "users#index"
  routes.add "post", "/users", "users#create"
end

As you may have noticed, our DSL for building up routes is a bit different than that implemented in Rails, but it has the same feel. Behind the scenes, we’re simply building up a Routes object with unique keys mapped to values that have meaning within the context of our framework.

Routing and Decorating Requests

So far, we have an augmented hash that maps verb-path keys to controller actions. Great. But how do we actually make use of these mappings? Furthermore, if we want to use something like a dynamic path segment (the :id in /users/:id), how do we go about sending the dynamic value along with the request?

Let’s start by looking at our application class, OnRackApp.

class OnRackApp
  def process_and_respond(env)
    request = Rack::Request.new(env)
    response = Rack::Response.new

    response = Router.new.route(request, response)
    response.finish
  end
end

Rack provides us with some helpful classes for handling requests and responses, Rack::Request and Rack::Response, respectively. The Rack::Request class, for instance, provides multiple params methods for retrieving request parameters (just like you see in the Rails controller). For now, we’ll isolate these class names in OnRackApp and allow our Router class to expect certain interfaces of request and response, rather than objects of specific classes. For some reason, I elected to take a more functional approach here, instantiating a Router object with no arguments and passing the request and response objects to the Router#route method. (Maybe this should be reconsidered?)

Let’s check out Router#route. As we move through these methods, you will continue to see a more functional style of data passing. There is mutation, but it does not occur on the state of the object. Rather, it occurs on the passed-around data. Again, there is design to be done here.

class Router
  ...
  def route(request, response)
    if mapping = map_and_parameterize(request)
      map_and_invoke_respond(mapping, request, response)
    else
      respond_to_absent_mapping(response)
    end
  end
  ...
end

Now our router has access to a request object, which has access to—among other properties—getters for request_method and path. You’ll recall that these are the two components that we used to create the unique route key (where request_method is the HTTP verb and path is the path). Thus, we can combine these properties to create a key with which we can access the controller#action mapping. We can route a request.

class Router
  ...
  private

  def map_and_parameterize(req)
    rkey = "#{req.request_method}##{req.path}"
    if mapping = Router::routes[rkey]
      return mapping
    end
    ...
  end
end

What happens, though, when we define a path with a dynamic route segment (e.g., /users/:id)? When we field a request for this route, we certainly won’t find it in this format. Instead, we expect to see a request path like /users/22. So, for dynamic route segments, our simple key construction falls flat.

Hope remains, of course. Because we receive a request path that has the same pattern as the dynamically segmented path we defined, we can in effect use pattern matching (Regexp) to not only find the appropriate mapping, but also to extract the segment name and value. I’m not by any means satisfied by the rigid approach I’ve taken to date, but it is functioning. That always makes for happy rabbits. You can check out router.rb here.

You’ll see that—because we can extract each dynamic route segment—we can add it to the request params (or further decorate the request object) before passing it along to the controller. Pretty neat stuff.

Racking Up

While there are plenty of gaps in the router and framework architecture we’ve discussed here, there is a real benefit in thinking through this kind of design. Ruby affords us the ability to create fun domain specific languages (DSLs), and building your own half-functional framework can be a great way to experiment with different techniques and language constructs. And you can make a frozen banana stand website, too.

Has Anybody Seen My Code?

The Ruby Rogues posted their Jim Weirich Tribute Episode on April 9th, 2014, a little over a month and a half having passed since Jim’s passing. Having first started practicing Ruby around a year ago, I admit that — while I certainly appreciated Rake — I hadn’t spent the time to get to know (from a distance, at least) the wonderful man behind the code.

Now, having fallen asleep many a night to a Jim Weirich conference talk, having perused the 100-line Ruby program that became Rake, and having read and/or listened to the anecdotes of Jim’s peers, it is clear to me that Jim Weirich was the friend, mentor, and creative innovator that any forward-thinking community needs. The anecdotes, in particular, have reminded me that the challenging of conventional thought is often the source of innovation. Moreover, the time we give to others is as valuable as the time we keep for ourselves.

At the crossroads of these two ideas stood Jim Weirich, a man who believed in his own opinions and gave others’ their time of day. We all can learn a lot from Jim the programmer and Jim the person. I know I have.

Loathe Doing Laundry? Scamper Whilst.

For me, doing laundry is generally one of those monotonous tasks that can bring an otherwise lively day to its knees. Be it the setting of a damp, unfinished basement; the jarring sound of the drier buzzer; or perhaps the infrequency with which I’ve had to attend to this necessary matter over the years, there is something about laundry that dims my mood. In fact, I’ve come to realize that laundry extracts from me and reveals of me a childish attitude – one not of glee, but of sluggish submission.

I’m not sure that I ever made a conscious decision to stop loathing laundry, but I do know that I learned to make it more enjoyable. How? Childish enthusiasm, of course.

One day, rather than slogging through the process, I decided to run – er, scamper, more appropriately. From the washer to the drier. From the drier to the washer. To and fro. Back and forth. Up and down the stairs (with tact, no doubt). Arms full of wet clothes and momentum on my side, I launched freshly plucked t-shirts and gold-toed socks through the dry basement air. My feet were nimble, my spirit alive. Surmounting my basement staircase, I wore a wry smile. I had conquered monotony.

I haven’t stopped doing laundry this way. I do my best to fly like the wind (Bullseye). Approach — in any walk of life — can make quite the difference.

Customize Named Model Attributes with ActiveModel::Serializers

If you’ve used ActiveModel::Serializers to serialize your Ruby objects into JSON (presumably in a Rails application), you’re familiar with the tools that Yehuda Katz’ brainchild affords us. When using Rails to build JSON APIs for front-end JavaScript applications (or general consumption), we can rely on ActiveModel::Serializers for serializing not only database-backed model attributes, but also custom attributes and associated records.

class GiraffeSerializer < ActiveModel::Serializer
  attributes :name, :age, :name_and_age, :height, :children

  def name_and_age
    "#{name} - #{age} year(s) old"
  end
end

In most applications, these features will suffice. However, when working on an AngularJS front-end recently, we sought to serialize a boolean model attribute as a string. The “why” is somewhat irrelevant, but it had something to do with a quirk in binding model attributes to form inputs in a directive. In any case, the task seemed simple. Perhaps something like the following would work.

class UserSerializer < ActiveModel::Serializer
  attributes :boolean_attribute

  def boolean_attribute
    boolean_attribute.to_s
  end
end

As you can probably see already, this isn’t a solution. The nasty feeling we permit when writing this code is accompanied by an ugly stack trace error. Onto the next one.

Luckily, “the next one” just so happens to be an ideal solution. If you seek to modify a model attribute (while retaining its name in serialization), you can do so by overriding the attributes method. (This is, in fact, documented.)

class UserSerializer < ActiveModel::Serializer
  attributes :email, :first_name, :last_name

  def attributes
    hash = super
    hash["boolean_attribute"] = object.boolean_attribute.to_s
    hash
  end
end

Notice that we leave boolean_attribute from the inital attributes call. This is because we’ve specified it explicitly in our custom attributes method. And with this, we’ve serialized our boolean attribute as a string without altering its name. (Note that object refers to the object being serialized.)

If you haven’t had the chance to dig into ActiveModel::Serializers yet, I recommend that you give it a go. This whole “JSON API in Rails” thing is pretty fun.

Listen for Cookie Change

I recently hacked around an interesting problem that involved executing some jQuery after setting several ZIP file download HTTP header fields. My initial thought was to make use of an AJAX post request to set the requisite headers and use the relevant deferred methods to take action on the response. Unfortunately, given the circumstances, this didn’t appear to be a viable option.

Download Complete?

I wanted to take some action (display a success message, in this case) after the download had been “forced.” And, for whatever reason, setting the headers seemed to disorient the script. (I say “disorient,” rather than “halt,” because commands after the header() declarations did execute.) In any case, I needed a different solution.

...
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
...

Eventually, this thought crossed my mind: If I can’t return data from this function (in which the headers are set), I’ll need some other way to communicate the appropriate message to the browser. Then, it occurred to me that this could be a job for cookies.

How the Cookie Crumbles

First, I would set a cookie on the initial page load.

...
setcookie('message', 'none');
...

Then, just before setting the headers in my ZIP download script, I would alter the cookie.

...
setcookie('message', $success_message);
header("Content-type: application/octet-stream");
...

Not complicated, I know. My form post would now take care of the ZIP download forcing and cookie value changing. But where did that get me?

Listen for Cookie Change

Since I wasn’t forcing the browser to reload the page (due to the placement of the new header commands and (probably) a lack of the right knowledge), I would need to actively “listen” for this cookie change in order to trigger the appropriate jQuery. Luckily, someone pieced together a neat little JSFiddle for the occasion. This made things simple.

listenCookieChange('message', function() {
    ...
    addMessage();
    ...
});

With a little effort, I had a solution that worked. It felt good.

As I mentioned, I’m sure there exists a much more elegant solution here. Thinking about these struggles (as I’ve unzipped them) has made this clearer. You live and you learn, I suppose.

First Commit

Actually, this Octopress blog is on its fourth commit; I sought to avoid using “Hello, World” in the inaugural sense. “Pilot” doesn’t do it for me, either, these days – no, I’ll leave the occupancy of that compartment of my mind to the first episode of The Office. In any case, this post marks a new beginning of sorts.

I’d like to leave an entry here from time to time, and I’d like to focus on (1) what I’ve been learning, (2) how I’ve been learning, and (3) why I’ve been learning. I’ll do my best to touch on each of these in every post; you have my word(s). Let us conclude for now, though, for this is merely a placeholder.