Changing User-Agent in Google Chrome

October 16, 2012

Here’s a Google Chrome pro-tip for you.  It’s easy to change the user-agent in Google Chrome dev builds with no extensions necessary:

  1. Open the inspector – by right clicking on any page and clicking “Inspect element”
  2. In the bottom right click the “Settings” gear
  3. Click into the “Overrides” tab
  4. Check user-agent, and select the one you want

Awesome time-saver, especially for those like me who hate installing extensions.

Tags

Proper Escaping of Single-quotes

If you’ve ever tried building up a command programatically, you may have run into some issues around proper quoting of arguments.

To solve most problems, you can just throw everything inside of a set single quotes. The shell won’t touch anything inside and you’ll be all good.

$ echo "$hello world" # " world" # or something worse
$ echo '$hello world' # "$hello world"

Then the one remaining question is what to do if you want to include a single quote? Your first inclination may be to escape it with a backslash:

$ echo '$hello \' world' # incomplete

But that’s not how it works :( The way you actually have to go about this is to stop the single-quote pair, escape a single quote, and then start it back up. Here it is:

$ echo '$hello '\'' world' # "hello ' world"

As a bonus, if you try to do this substitution in Ruby, you may try something like:

var = 'hello \' world'
var.gsub('\'', '\'\\\'\'') # "hello ' world' world"

Wat!? That’s not what you wanted! Read that documentation!  Let’s try again

var.gsub('\'') { '\'\\\'\'' } # "hello '\\'' world"

There we go! Make it a little prettier even:

var.gsub("'") { %q{'\'} }

Tags

Dependency Injection in JavaScript Tests

September 9, 2012

When you’re writing tests in Node, its often useful to be able to stub out modules which are included by the object you’re attempting to test.  Unfortunately due to the way that the module system is structured, its not straightforward to do this in a single test (as opposed to globally).

There are a few solution for this dependency injection problem around, namely node-sandboxed-module and injectr.  These modules use node’s vm module to create a new context that they run the test inside of, and in that context they use the mock instead of the original when calling `require`.  This is a nice solution, but unfortunately by bringing the code into a new context, you also break code analysis tools like mocha’s html-cov.

A few days ago, Matt Morgan released a module called mockit, which approaches the problem instead by temporarily replacing `require` when requiring the dependency the test needs (as opposed to trying to replace it for the duration of the test).

Imagine you had a `Downloader` class, and you wanted to use it in your tests, but have it so that when `Downloader` called `require(‘http’);`, it got a mock instead of node’s http class.  You could do that with one call to mockit:

var Downloader = mockit('../lib/downloader', {
  http: mockHttp
});

I think this is a really nice solution to this problem – totally unobtrusive and uses node’s existing `require` functionality when no mock exists. Check it out!

JavaScript Callstacks

September 4, 2012

Today I’m going to share a cool method for generating a JavaScript callstack from any point in your code.  JavaScript doesn’t offer this functionality, but we can tease it out pretty easily, especially in V8 (very useful for Node programmers).

The closest thing JavaScript has to a callstack is the 10-frame backtrace that comes along whenever an error is generated.  So we can use that to our advantage, by generating an error on-demand, catching the response, and examining the #stack attribute of the thrown error object:

function callstack() {
  try { capture.error } catch (e) {
    return e.stack;
  }
}

Normally we’d have to stop there, and if we wanted to access that data programatically we’d have to parse the pre-formatted String that comes back.  But with V8 we have a better option!  V8 gives us access to the method that prepares the preformatted response, so by temporarily replacing it – we can return the original data instead.  Check it out, here’s a small node.js module:

var replacementPreparer = function (error, trace) {
  return trace;
};

module.exports = function () {
  var capture;
  var oldPreparer = Error.prepareStackTrace;
  Error.prepareStackTrace = replacementPreparer;
  try { capture.error } catch (e) {
    capture = e.stack;
  }
  Error.prepareStackTrace = oldPreparer;
  return capture;
};

And the usage:

var callstack = require('./path/to/callstack/js');
for (var i = 0; i < 1000; i++) {
  callstack(); // use this anywhere in your code
}

When you call `callstack`, you’ll get back an array of CallSite objects upon which you can call methods from the V8 API to get at all the juicy details: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi

Tags

Ruby Gotcha: single line conditionals

July 31, 2012

I’ve touched on this gotcha briefly in the past when discussing the Wat video, but I thought a few examples of when single-line conditionals can bite you would be fun.

In Ruby, we can write a conditional containing a single expression that normally takes up three lines:

unless condition
  something
end

on a single line to save space:

something unless condition

And that is all well and good – these two are pretty much the same.  But they’re not identical in practice. There are a few weird things about to come up.

Our first example will be using defined? to conditionally print a variable

if defined?(var1)
  puts var1 # never runs
end

var1 # NameError: undefined local variable

So that works just as we’d expect. The conditional never runs because defined?(var1) returns nil. After the conditional, access the undefined var1 gives us a NameError because (appropriately) its not defined. Let’s modify that a little bit and put an assignment inside of the conditional.

if defined?(var2)
  var2 = 5 # never runs
end

var2 # nil
defined?(var2) # "local-variable"

So that might look a bit odd.  We never ran the conditional, so var2 never gets set – that makes sense.  But after the block, var2 doesn’t throw a NameError when accessed anymore. This is because the Ruby parser makes room and defines var2 when it sees it on the lefthand side of an expression (even though its inside of a conditional that doesn’t run).

Let’s write the same on one line though:

var3 = 5 if defined?(var3)

var3 # 5

Even more interesting – an undefined variable written this way will become defined and assigned when run.  The first thing that happens is that the parser comes along and defines var3 which it sees on the lefthand side of a conditional.  Then defined? runs, which this time evaluates to "local-variable", causing the conditional to pass, and 5 to be assigned to var3.  In cases like this, the single-line conditional will produce an entirely different result than block conditionals.

Tags