Archive for November, 2008

Quotes in code: Turning off smart quotes in WordPress

Posted on November 6th, 2008 No Comments »

I'm new to WordPress and recently had the following issue: Some (though oddly not all) single and double quotes in code snippets were being converted to curly quotes which a) looked bad and b) caused them to be ignored by the syntax highlighter I'm using (Dan Webb's CodeHighlighter). This helpful thread offers several ways to address the issue: http://wordpress.org/support/topic/125038. Though I'm beginning to feel a bit queasy about WordPress.

Extending Prototype to parse model ID from DOM ID

Posted on November 6th, 2008 No Comments »

Consider a simple list of to-do tasks:

<ol class="tasks">
  <li id="task-1">run</li>
  <li id="task-2">vote</li>
  <li id="task-3">code</li>
</ol>

There are three task instances (with ids 1, 2, 3), each of which is rendered as a list element referenceable by DOM id. Note the id format: <model>-<id>, e.g. "task-1". This pattern is frequently used to avoid collisions with ids for other models because DOM ids are global and cannot be qualified to a particular object type or namespace (e.g. Task v. Group). When using the <model>-<id> format, you'll often want to obtain just the model id portion, say, to send to the server to edit or delete a task. After you've written code like this a few times:

var modelId = element.id.split('-').last();

you'll be overcome by a strong urge to extract a method that hides the ugly and standardizes the approach. I use the Prototype library at work, so I've implemented a utility method as an extension to Prototype's Element, making it available to any html element obtained via $() or $$(). However, the idea is easily implemented in jQuery or a library-agnostic manner. Here's the code:

/*
 * Prototype Element extensions
 */
Element.addMethods({
  /**
  * Returns last delimited portion of dom id for id or element passed where element id is of the form:
  *   example-<id> OR example_<id>
  * Supports hyphen '-' or underscore '_' as delimiter. Returns null if element id is missing or does not
  * contain a delimiter. Some example ids:
  *   task-group-25 // Returns 25
  *   25 // Returns null; use element.id instead
  */
  modelId: function(element) {
    var id = $(element).id;
    if (id == null) return null; // Just in case; browsers tested return empty string for missing id.	

    var idParts = id.split(/[-_]/g);
    return (idParts.length > 1) ? idParts.last() : null;
  }
});

/*
 * Usage
 */

// Get single task id
$('task-1').modelId(); // Returns "1"

// Get all task ids
$$('.tasks li').invoke('modelId'); // Returns ["1","2","3"]

Sometimes a String is just a String. Or not.

Posted on November 4th, 2008 5 Comments »

JavaScript, I love you, but I will never understand you. From the Firefox console:

>>> typeof 'test'
"string"

>>> 'test' instanceof String
false

>>> s = new String('test')
>>> typeof s
"object"

>>> s instanceof String
true

So the string "test" can be a "string", not a String, an "object" or a String. Good times. Then there's my personal favorite:

>>> typeof null
"object"

Null is an object? I object. In Ruby, nil is a full-blown object but in JavaScript, null is not. So when it comes to typeof, be careful what you ask for.

Douglas Crockford, perhaps the Godfather of JavaScript, comments further on typeof weirdness and offers an improved implementation.

Daylight Ravings

Posted on November 3rd, 2008 6 Comments »

Any developer who's had to deal with Date/Time calculations knows there are myriad issues to navigate, particularly around time zone and Daylight Saving handling. Today (Mon 2008.11.03), I ran our tests and stumbled upon the following code (simplified for this post) that was breaking:

# relapse_test.rb
def test_middle_time
  t = Time.now
  r = Relapse.new(:start_time => t-5.days, :end_time => t-1.day)
  middle = t-3.days
  assert_equal middle, r.middle_time # Breaking on Mon 2008.11.03
end

# Relapse class in relapse.rb
def middle_time
  return start_time + (end_time - start_time)/2
end

Results of the test:

<Fri Oct 31 11:27:18 -0400 2008> expected but was
<Fri Oct 31 11:57:18 -0400 2008>.

The purpose of middle_time() is to return the time halfway between the start and end times. The code seemed straightforward, but for some reason, the expected and returned values differed by 30 minutes.

As I stared at the code, there was another nagging question - why was this happening now when it wasn't prior, before the weekend. Hmmm ... a Halloween trick? To get more insight, I added some print statements to echo the times used by the middle_time calculation and got the following:

Start: Wed Oct 29 11:27:18 -0400 2008
  End: Sun Nov 02 11:27:18 -0500 2008

Bingo. Check out the time zone offset: -0400 for start time and -0500 for end. What happened over the weekend? Halloween in Salem was a good guess but the culprit was the switch from Daylight Saving back to Standard Time. Because of the time zone disparity, there is an extra hour between the start time, taking place in Daylight Saving time, and the end time in Standard Time. So (end_time - start time) in middle_time() adds an extra hour (4 days plus one hour) and, when divided by 2, produces the 30 minute discrepancy between expected and actual time.

Proper handling depends on your situation. In ours, we were interested in the middle DATE rather than the time, so the implementation was changed to use dates v. times. For situations where time does matter, the 30 minute discrepancy may, in fact, be desired as it factors in the number of hours that have elapsed. But if you want the calculation to be time zone-consistent (or agnostic), you can use the UTC (GMT) time zone; Time.now.utc returns the current UTC time. Calculations can be performed in UTC, which does not shift for Daylight Saving (or any other reason), and converted back to a zone-specific time as needed.