<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">
    <title>Swivel Code Blog</title>
    
    <link rel="hub" href="http://hubbub.api.typepad.com/" />
    <link rel="alternate" type="text/html" href="http://blog.swivel.com/code/" />
    <id>tag:typepad.com,2003:weblog-1288418</id>
    <updated>2009-11-02T16:35:02-08:00</updated>
    <subtitle>The code blog is full of yummy code snippets.</subtitle>
    <generator uri="http://www.typepad.com/">TypePad</generator>
    <link rel="self" href="http://feeds.feedburner.com/typepad/huned/swivelcode" type="application/atom+xml" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><entry>
        <title>Changing its spots ... OrderedHash chaos in Leopard</title>
        <link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/typepad/huned/swivelcode/~3/S233xwQPiH4/changing-its-spots-orderedhash-chaos-in-leopard.html" />
        <link rel="replies" type="text/html" href="http://blog.swivel.com/code/2009/11/changing-its-spots-orderedhash-chaos-in-leopard.html" thr:count="0" />
        <id>tag:typepad.com,2003:post-6a00d8341c8db453ef0120a64c9523970b</id>
        <published>2009-11-02T16:35:02-08:00</published>
        <updated>2009-11-06T10:43:15-08:00</updated>
        <summary>UPDATE: The brilliant people at MacPorts have fixed the bug we encounter below. To upgrade: svn checkout http://svn.macports.org/repository/macports/trunk/dports/lang/ruby/ cd ruby sudo port install Sometimes, you find yourself using hashes as keys in a hash. It gets meta: Item.all.group_by{ |i| i[:attrs]...</summary>
        <author>
            <name>Ben Walsh</name>
        </author>
        <category scheme="http://www.sixapart.com/ns/types#category" term="rails" />
        
        
<content type="html" xml:lang="en-US" xml:base="http://blog.swivel.com/code/">
&lt;div xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;p&gt;&lt;b&gt;UPDATE:&lt;/b&gt; The brilliant people at MacPorts have &lt;a href="https://trac.macports.org/ticket/22361"&gt;fixed the bug&lt;/a&gt; we encounter below. To upgrade:&lt;/p&gt;

&lt;p&gt;&lt;pre&gt;
svn checkout http://svn.macports.org/repository/macports/trunk/dports/lang/ruby/
cd ruby
sudo port install
&lt;/p&gt;&lt;/pre&gt;

&lt;hr/&gt;

&lt;p&gt;Sometimes, you find yourself using hashes as keys in a hash. It gets meta:&lt;/p&gt;

&lt;p&gt;&lt;pre&gt;
Item.all.group_by{ |i| i[:attrs] }
&lt;/pre&gt;&lt;/p&gt;

&lt;p&gt;Where &lt;code&gt;attrs&lt;/code&gt; is a hash like this:&lt;/p&gt;

&lt;p&gt;&lt;pre&gt;
{ :id =&gt; Fixnum, :type =&gt; String }
&lt;/pre&gt;&lt;/p&gt;

&lt;p&gt;After a recent upgrade of some vendor code, some of us starting seeing test failures around that &lt;code&gt;group_by&lt;/code&gt; code, and some didn't, although we were all on the same ruby version and patchlevel. The tests were still passing on the build server. And the failures made no sense -- the values of the hash were nil.&lt;/p&gt;

&lt;p&gt;After some head-scratching, we found that Ruby running on Mac OS Leopard can't handle hashes with large numbers as values very well.&lt;/p&gt;

&lt;p&gt;&lt;pre&gt;
&gt;&gt; {:a =&gt; 536870911}.hash == {:a =&gt; 536870911}.hash
    =&gt; true
&gt;&gt; {:a =&gt; 536870912}.hash == {:a =&gt; 536870912}.hash
    =&gt; false
&lt;/pre&gt;&lt;/p&gt;

&lt;p&gt;And "large numbers" are exactly what you get as default ids for fixture-created ActiveRecord objects in Rails tests. The key being assigned to and the key being read from were identical, except they weren't.&lt;/p&gt;

&lt;p&gt;It turns out that in the Leopard environment running MacPorts the items would never have been grouped properly, but in production everything looked fine. The upgrade to Rails we made included some enhancements to &lt;code&gt;Enumerable#group_by&lt;/code&gt; to sort the output as an &lt;code&gt;OrderedHash&lt;/code&gt;, and that exposed us to the bug -- now, instead of just failing to group the results properly, it was breaking. Those who had recently upgraded to Snow Leopard did not have the same problem -- and our servers, obviously, were immune.&lt;/p&gt; 
&lt;/div&gt;
</content>


    <feedburner:origLink>http://blog.swivel.com/code/2009/11/changing-its-spots-orderedhash-chaos-in-leopard.html</feedburner:origLink></entry>
    <entry>
        <title>Sending Email with ActionMailer -- New! Improved! DRYer!</title>
        <link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/typepad/huned/swivelcode/~3/fR6LnCMqcFY/sending-email-with-actionmailer-new-improved-dryer.html" />
        <link rel="replies" type="text/html" href="http://blog.swivel.com/code/2009/10/sending-email-with-actionmailer-new-improved-dryer.html" thr:count="0" />
        <id>tag:typepad.com,2003:post-6a00d8341c8db453ef0120a60d0539970c</id>
        <published>2009-10-02T11:26:49-07:00</published>
        <updated>2009-10-02T11:26:49-07:00</updated>
        <summary>In a previous post, we talked a bit about DRYing up email. You can alias all the methods for delivering different types of email at a generic method, and then simply control all the differences at the template level: ['feedback',...</summary>
        <author>
            <name>Ben Walsh</name>
        </author>
        
        
<content type="xhtml" xml:lang="en-US" xml:base="http://blog.swivel.com/code/">
<div xmlns="http://www.w3.org/1999/xhtml">
<p>In a <a href="http://blog.swivel.com/code/2008/08/sending-email-w.html">previous post</a>, we talked a bit about DRYing up email. You can alias all the methods for delivering different types of email at a generic method, and then simply control all the differences at the template level:</p>

<pre>
  ['feedback', 'sales', 'hate'].each { |t| alias_method t.to_sym, :message }
</pre>

<p>Of course, leaving well enough alone isn't something we do, and the idea of having to update that hard-coded list of templates doesn't seem logical. All the templates will live in the <code>views/notifier</code> directory, so why not just pull them from there when the app starts up?</p>

<p>Within the <code>Notifier</code> model, instead of the hard-coded line above, create a class method that calls <code>alias_method</code> on each element in an array:</p>

<pre>
  def self.templates= templates
    templates.each do |t|
      alias_method(t.to_sym, :message)
    end
  end
</pre>

<p>Then, create a new initializer called something like <code>config/initializers/populate_email_templates.rb</code> which just has this handy one-liner:</p>

<pre>
  Notifier.templates= Dir.new("#{Rails.root}/app/views/notifier").entries.map{|f| File.basename(f, '.html.erb')}
</pre>

<p>Kick the server so it picks up the changes, and you're good to go. Now when you create (or delete) an email template, all the plumbing and wiring is already done and it should just work.</p>

</div>
</content>


    <feedburner:origLink>http://blog.swivel.com/code/2009/10/sending-email-with-actionmailer-new-improved-dryer.html</feedburner:origLink></entry>
    <entry>
        <title>Integration testing -- even your emails aren't safe</title>
        <link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/typepad/huned/swivelcode/~3/qdgt98VG_Ws/integration-testing-even-your-emails-arent-safe.html" />
        <link rel="replies" type="text/html" href="http://blog.swivel.com/code/2009/09/integration-testing-even-your-emails-arent-safe.html" thr:count="0" />
        <id>tag:typepad.com,2003:post-6a00d8341c8db453ef0120a5930c79970b</id>
        <published>2009-09-23T14:00:06-07:00</published>
        <updated>2009-09-23T14:00:06-07:00</updated>
        <summary>An integration-test related thought suddenly struck me: often you'll send an email that includes an action item as a link. Sometimes that link will actually do something -- confirm a change you've made, for example. Now, of course you're testing...</summary>
        <author>
            <name>Ben Walsh</name>
        </author>
        <category scheme="http://www.sixapart.com/ns/types#category" term="code" />
        
        
<content type="xhtml" xml:lang="en-US" xml:base="http://blog.swivel.com/code/">
<div xmlns="http://www.w3.org/1999/xhtml">


<p>An integration-test related thought suddenly struck me: often you'll send an email that includes an action item as a link. Sometimes that link will actually do something -- confirm a change you've made, for example. Now, of course you're testing the path that the email is supposed to include, but why not go one further and test that the link that's actually in your email will have the desired effect?</p>

<pre>
[ ... send out the email .. ]
assert_change('Person.find(people(:one).id).confirmed?', 'false', 'true') do 
  assert_select_email do
    get(assert_select('a').first['href'])
  end
end
</pre>

<p>You should clear out the deliveries array first, or it might try to operate on the wrong email. I just put this line in the <code>setup</code> method:</p>

<pre>ActionMailer::Base.deliveries = []</pre>

<p>Never heard of <code>assert_change</code>, you say? It's a riff on <code>assert_difference</code> that might find a home in a <code>test_helper.rb</code> file near you:</p>

<pre>
  def assert_change(field, from, to)
    initial = eval(field).to_s
    assert_match(initial, from)
    yield
    assert_equal(initial.gsub(from, to), eval(field).to_s)
  end
</pre>
</div>
</content>


    <feedburner:origLink>http://blog.swivel.com/code/2009/09/integration-testing-even-your-emails-arent-safe.html</feedburner:origLink></entry>
    <entry>
        <title>A Quick One, While He's Away</title>
        <link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/typepad/huned/swivelcode/~3/CVcl3dyTPHo/a-quick-one-while-hes-away.html" />
        <link rel="replies" type="text/html" href="http://blog.swivel.com/code/2009/09/a-quick-one-while-hes-away.html" thr:count="0" />
        <id>tag:typepad.com,2003:post-6a00d8341c8db453ef0120a58df7ef970b</id>
        <published>2009-09-22T11:41:48-07:00</published>
        <updated>2009-09-22T11:41:48-07:00</updated>
        <summary>I ran into a small problem using assert_select_email -- it expects multipart messages, and those we are sending are not. A quick and dirty solution was to included the following ugly monkeypatch rewrite of the SelectorAssertions in our test_helper file:...</summary>
        <author>
            <name>Ben Walsh</name>
        </author>
        <category scheme="http://www.sixapart.com/ns/types#category" term="code" />
        
        
<content type="html" xml:lang="en-US" xml:base="http://blog.swivel.com/code/">
&lt;div xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;p&gt;I ran into a small problem using &lt;code&gt;assert_select_email&lt;/code&gt; -- it expects multipart messages, and those we are sending are not.&lt;/p&gt;

&lt;p&gt;A quick and dirty solution was to included the following ugly monkeypatch rewrite of the SelectorAssertions in our &lt;code&gt;test_helper&lt;/code&gt; file:&lt;/p&gt;

&lt;pre&gt;
module ActionController
  module Assertions
    module SelectorAssertions
      def assert_select_email(&amp;block)
        deliveries = ActionMailer::Base.deliveries
        assert(!deliveries.empty?, "No e-mail in delivery list")
        for delivery in deliveries
          &lt;span style="color:#f00"&gt;for part in delivery.parts.empty? ? [delivery] : delivery.parts.select{|p| p["Content-Type"].to_s =~ /^text\/html\W/}&lt;/span&gt;
            root = HTML::Document.new(part.body).root
            assert_select(root, ":root", &amp;block)
          end
        end
      end
    end
  end
end

&lt;/pre&gt;
&lt;/div&gt;
</content>


    <feedburner:origLink>http://blog.swivel.com/code/2009/09/a-quick-one-while-hes-away.html</feedburner:origLink></entry>
    <entry>
        <title>You And Me Baby Ain't Nothing But YAMLs</title>
        <link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/typepad/huned/swivelcode/~3/4wqK7L25W1U/you-and-me-baby-aint-nothing-but-yamls.html" />
        <link rel="replies" type="text/html" href="http://blog.swivel.com/code/2009/09/you-and-me-baby-aint-nothing-but-yamls.html" thr:count="0" />
        <id>tag:typepad.com,2003:post-6a00d8341c8db453ef0120a56f30a0970b</id>
        <published>2009-09-14T16:43:44-07:00</published>
        <updated>2009-10-08T10:28:58-07:00</updated>
        <summary>Javascript testing has come a long way from the days when it didn't exist. We've touched on the Scriptaculous unit testing framework in this space before, but the nature of a web application that's heavily AJAX-dependent is that you need...</summary>
        <author>
            <name>Ben Walsh</name>
        </author>
        <category scheme="http://www.sixapart.com/ns/types#category" term="code" />
        
        
<content type="html" xml:lang="en-US" xml:base="http://blog.swivel.com/code/">
&lt;div xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;p&gt;Javascript testing has come a long way from the days when it didn't exist. We've touched on the &lt;a href="http://wiki.github.com/madrobby/scriptaculous/unit-testing"&gt;Scriptaculous unit testing framework&lt;/a&gt; in this space before, but the nature of a web application that's heavily AJAX-dependent is that you need to be absolutely sure the server and the client are in agreement, and for testing purposes this means that your framework tests and your Javascript tests have to be on the same page.&lt;/p&gt;

&lt;p&gt;That page has a few requirements. It needs to be accessible from an HTML page that is accessed via the &lt;code&gt;file:///&lt;/code&gt; protocol -- you'll always need the option of running your tests in isolation, locally, rather than only through &lt;code&gt;rake test:javascripts&lt;/code&gt;. It needs to be something that can be populated and maintained easily by humans. It needs to be lightweight. And it needs to be usable by both our Rails tests and our Javascripts tests. So, given the Rails paradigm of using YAML to maintain test fixtures, why not start there? Let's create an &lt;code&gt;ajax_fixtures.yml&lt;/code&gt; file in &lt;code&gt;test/javascripts&lt;/code&gt; and populate it with the AJAX requests and responses we want to test, as YAML data:&lt;/p&gt;

&lt;pre&gt;
requests:
    save:
        value: 1
	quantity: 3
	id: 1

responses:
    save:
	result: Item successfully saved
&lt;/pre&gt;


&lt;p&gt;An integration test called &lt;code&gt;test/integration/ajax_test.rb&lt;/code&gt; is the way we roll when it comes to testing all AJAX interactions from the server perspective. In the setup method, load up the Ajax requests so they're available to every test:&lt;/p&gt;

&lt;pre&gt;
def setup
    @ajax = YAML.load(File.open("#{Rails.root}/test/javascript/ajax_fixtures.yml").read)
end
&lt;/pre&gt;

&lt;p&gt;Now, to test the "save" AJAX request, you can access the &lt;code&gt;@ajax['requests']['save']&lt;/code&gt; and see if sending that request has the desired effect:&lt;/p&gt;

&lt;pre&gt;
test("saving") do
    post(item_path(items(:one), :format =&gt; 'json'), :item =&gt; @ajax['requests']['save'].to_json) 
    assert_equal(3, assigns(:item).quantity)
end
&lt;/pre&gt;

&lt;p&gt;Well, that's straightforward enough and, so far as it goes, unnecessary. But let's think of that YAML file as a &lt;b&gt;contract&lt;/b&gt; between the server and client components of the app. The Javascript tests have to prove that the right circumstances will generate the requests and handle to the responses, while the Rails tests must prove that they can interpret the requests and provide the expected responses. The Rails tests can easily handle our YAML file, but the Javascript tests might need a little help. First, we need to the YAML to HTML so that all browsers can load it. This is easily done with a &lt;code&gt;rake&lt;/code&gt; task which you can drop into &lt;code&gt;lib/tasks/somefile.rake&lt;/code&gt;. Choose which &lt;code&gt;rake&lt;/code&gt; testing tasks should invoke the YAML task -- the whole test suite, obviously, and any that might be AJAX-related:&lt;/p&gt;

&lt;pre&gt;
task :test =&gt; 'ajax:prepare'
namespace :test do
    [:integration, :javascript].each{ |t| task t =&gt; 'ajax:prepare' }
end

namespace :ajax do
    desc "Prepare AJAX test fixtures"
    task :prepare do
        json = YAML.load(File.open("#{Rails.root}/test/javascript/ajax_fixtures.yml")).to_json
        File.open("#{Rails.root}/test/javascript/ajax_fixtures.html", 'w').puts(json)
    end
end
&lt;/pre&gt;

&lt;p&gt;This snippet will execute before you run &lt;code&gt;rake&lt;/code&gt; or one of the specified tasks, and will write out the structured YAML to a big blob of JSON which is not very human-readable, but your Javascript test file can grab via a simple Ajax call:&lt;/p&gt;

&lt;pre&gt;
  &amp;lt;script type="text/javascript"&amp;gt;
    new Ajax.Request('ajax_fixtures.html', {
      asynchronous: false,
      method: 'get',
      onSuccess: function(t) {
        expectedAjax = t.responseText.evalJSON();
      }
    });
  &amp;lt;/script&amp;gt;
&lt;/pre&gt;


&lt;p&gt;Also in our javascript test file, we're going to call on &lt;a href="http://drnicutilities.rubyforge.org/drnic_js_test_helpers/"&gt;Dr Nic&lt;/a&gt; for some help mocking out the Ajax requests:

&lt;pre&gt;
 &amp;lt;script src="assets/drnic_js_test_helpers.js" type="text/javascript"&amp;gt;&amp;lt;/script&amp;gt;

 ...

 testSave: function() { with(this) {

   Test.Ajax.setupMock('/items/1/save.json', function(request, response) {
      ajaxRequestCount++;
      ajaxRequestJSON = request.options.parameters.evalJSON();
    }.bind(this));


   ajaxRequestCount = 0;
   ajaxRequestJSON = '';
 
   // invoke javascript 'save' method //

   assertEqual(1, ajaxRequestCount); // the Ajax Request has been called
   
   // compare the &lt;strong&gt;expectedAjax['requests']['save']&lt;/strong&gt; data (from YAML)
   // with the &lt;strong&gt;ajaxRequestJSON&lt;/strong&gt; data actually passed to the Ajax.Request method

  }}
&lt;/pre&gt;

&lt;p&gt;Remember to run &lt;code&gt;Test.Ajax.clearMocks()&lt;/code&gt; when you're done --the &lt;code&gt;teardown&lt;/code&gt; method is the best place for this. Now you've loaded &lt;i&gt;the same information&lt;/i&gt; into your Javascript test and your Rails test and if the two agree, then you're really getting somewhere.&lt;/p&gt;

&lt;h2&gt;Special bonus section!&lt;/h2&gt;

&lt;p&gt;Comparing &lt;code&gt;expectedAjax&lt;/code&gt; and &lt;code&gt;ajaxRequestJSON&lt;/code&gt; can get a bit tricky if you have complicated nested objects. Here's a little object comparison method I wrote for this purpose, seen here as a standalone function. It requires &lt;a href="http://www.prototypejs.org"&gt;Prototype&lt;/a&gt;:&lt;/p&gt;

&lt;pre&gt;
    function hashEqual(a, b) {
      if ((!a) &amp;&amp; (!b)) { return true;}
      if (!a.keys) { a = $H(a); } if (!b.keys) { b = $H(b);}
      if ( String(a.keys().sort()) != String(b.keys().sort())) { return false; }
      var r = a.keys().map(function(k) {
        var a_val = a.unset(k);
        var b_val = b.unset(k);
        if (typeof(a_val) == 'object') {
          return (hashEqual(a_val, b_val));
        } else if (a_val != b_val) {
          return false;
        } else { return true;}
      }.bind(this)).uniq();
      return(r.reject(function(e) { return(e); }).length == 0);
    };
&lt;/pre&gt;


&lt;/div&gt;
</content>


    <feedburner:origLink>http://blog.swivel.com/code/2009/09/you-and-me-baby-aint-nothing-but-yamls.html</feedburner:origLink></entry>
    <entry>
        <title>Faking Keyboard Events in Safari: A Work in Progress</title>
        <link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/typepad/huned/swivelcode/~3/GKivSP5eSsY/faking-keyboard-events-in-safari-a-work-in-progress.html" />
        <link rel="replies" type="text/html" href="http://blog.swivel.com/code/2009/09/faking-keyboard-events-in-safari-a-work-in-progress.html" thr:count="0" />
        <id>tag:typepad.com,2003:post-6a00d8341c8db453ef0120a5b4c12a970c</id>
        <published>2009-09-09T15:32:33-07:00</published>
        <updated>2009-09-09T15:32:33-07:00</updated>
        <summary>Usually we use this space to bring you carefully-crafted solutions to problems we've encountered, and if I had solved this particular problem that's what I'd do now. In this case, I'm not entirely sure if a solution exists or if...</summary>
        <author>
            <name>Ben Walsh</name>
        </author>
        
        
<content type="xhtml" xml:lang="en-US" xml:base="http://blog.swivel.com/code/">
<div xmlns="http://www.w3.org/1999/xhtml"><p>Usually we use this space to bring you carefully-crafted solutions to problems we've encountered, and if I had solved this particular problem that's what I'd do now. In this case, I'm not entirely sure if a solution exists or if I've come up against a browser bug, and I've exhausted the Internet's collective wisdom on the subject. So here's the state of play as regards creating keyboard events in Safari/Webkit.</p>

<p>One of the many great things the <a href="http://wiki.github.com/madrobby/scriptaculous/unit-testing">scriptaculous unit testing framework</a> provides is the ability to mock events using <code>Event.simulateKey</code> and <code>Event.simulateMouse</code>.</p>

<p>Of course, given the state of cross-browser event <i>handling</i>, it should be no surprise that cross-browser event <i>creation</i> is a hairy beast. Scriptaculous uses the <code>createEvent</code> to (unsurprisingly) create events, with <code>document.createEvent("KeyEvents");</code>, and Safari/Webkit immediately gives this up as a bad job with <code>NOT_SUPPORTED_ERR: DOM Exception 9</code>. More acceptable is <code>document.createEvent("KeyboardEvent")</code>, which will work in most browsers.</p>

<p>Now that we have an event, we pass <code>initKeyEvent</code> with a long list of options including <code>keyCode</code> and <code>charCode</code>, the parameter so great they named it twice and implemented it slightly differently and caused enormous amounts of confusion. Safari/Webkit, though, has no time for this sort of carry-on and requires the W3C standard <code>initKeyboardEvent</code>, which takes a different list of different options. The character codes have been replaced with a <code>keyIdentifier</code> and <code>keyLocation</code> instead -- the first being the Unicode for the key being pressed (or the string "undefined") and the second specifying which key when several keys have the same value (a number on the numeric keypad versus its normal number key, for example). Finally, instead of booleans for the shift, alt, control, and meta key states, as <code>initKeyEvent</code> requires, <code>initKeyboardEvent</code> takes a <code>modifiers</code> argument, which is a string of whitespace-delimited names. The event itself will still have the <code>keyCode</code> and <code>charCode</code> attributes so your event handler code will work, but these are readonly and cannot be passed as arguments.</p>

<p>So, my tentative reworking of <code>event.simulateKey</code> might look a bit like this:</p>

<pre>
<span style="color:green;">Event.simulateKey = function(element, eventName) {
  var options = Object.extend({
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    keyCode: 0,
    charCode: 0
  }, arguments[2] || {});</span><span style="color:red;">
  var oEvent = document.createEvent("KeyboardEvent");
  try {</span><span style="color:green;">
  oEvent.initKeyEvent(eventName, true, true, window, 
    options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
    options.keyCode, options.charCode );</span><span style="color:red;">
  } catch(e) {
    var modifiers = [];
    if (options.shiftKey) { modifiers.push('Shift'); }
    if (options.ctrlKey) { modifiers.push('Control'); }
    if (options.altKey) { modifiers.push('Alt');}
    var keyLocation = '0x00';
    var keyIdentifier = 'U+00'+options.keyCode.toString(16);
    oEvent.initKeyboardEvent(eventName, true, true, window, keyIdentifier,
keyLocation, modifiers.join(' '));
  }</span><span style="color:green;">
    $(element).dispatchEvent(oEvent);
</span></pre>

<p>So, I've done what I can to placate the Safari gods and create a <code>keyboardEvent</code> according to spec -- but it seems that whatever you do, you simply cannot get Safari to create a keyboard event that truly emulates a real system keyboard event.</p>

<p><a style="display: inline;" href="http://blog.swivel.com/.a/6a00d8341c8db453ef0120a55e43d9970b-pi"><img class="at-xid-6a00d8341c8db453ef0120a55e43d9970b" alt="Inspecting the keyboardEvent in Safari" title="Inspecting the keyboardEvent in Safari" src="http://blog.swivel.com/.a/6a00d8341c8db453ef0120a55e43d9970b-800wi" border="0" /></a></p>

<p>The <code>keyCode</code> and <code>charCode</code> attributes are stubbornly reset to <code>0</code> and the goal of running our entire test suite on Apple browsers remains. What results have other folks had, and what alternatives exist?</p>
</div>
</content>


    <feedburner:origLink>http://blog.swivel.com/code/2009/09/faking-keyboard-events-in-safari-a-work-in-progress.html</feedburner:origLink></entry>
    <entry>
        <title>Sharp threads</title>
        <link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/typepad/huned/swivelcode/~3/zLN35bjr2sA/sharp-threads.html" />
        <link rel="replies" type="text/html" href="http://blog.swivel.com/code/2009/08/sharp-threads.html" thr:count="0" />
        <id>tag:typepad.com,2003:post-6a00d8341c8db453ef0120a51ccee5970b</id>
        <published>2009-08-25T12:18:02-07:00</published>
        <updated>2009-08-25T12:18:02-07:00</updated>
        <summary>When you come to a .fork in a Process, take it. A foible of Ruby forked processes is that children have copies of the parent process's objects. In the case of the ActiveRecord::Base.connection_pool, this means that usually when you try...</summary>
        <author>
            <name>Ben Walsh</name>
        </author>
        <category scheme="http://www.sixapart.com/ns/types#category" term="rails" />
        
        
<content type="xhtml" xml:lang="en-US" xml:base="http://blog.swivel.com/code/">
<div xmlns="http://www.w3.org/1999/xhtml"><p>When you come to a <code>.fork</code> in a <code>Process</code>, take it.</p>

<p>A foible of Ruby forked processes is that children have <i>copies</i> of the parent process's objects. In the case of the <code>ActiveRecord::Base.connection_pool</code>, this means that usually when you try to start new database connections within a forked process, you won't.</p>

<p>When a complex database migration requires a lot of horsepower and raw SQL executes, rather than allowing ActiveRecord to take its course, you will likely benefit from forking the task. But you may also want to ensure that your database connections are unique to each process.</p>

<p>Much of the advice out there focuses on how important it is to teardown the existing connection before forking, have each process create its own connection, and then reset the old connection at the end. And this is good as far as it goes, but it's not the whole picture. If you simply remove the connection, and then establish a new connection in each process, the connection_pool is going to look the same to each process and thus the "new" connection each time will actually be the same one:</p>

<pre>
  ActiveRecord::Base.remove_connection
  4.times do
    Process.fork do
      ActiveRecord::Base.establish_connection
      puts connection
      ActiveRecord::Base.remove_connection
    end
  end
  Process.waitall
  ActiveRecord::Base.establish_connection
</pre>

<p>outputs:</p>

<pre>
  #&lt;ActiveRecord::ConnectionAdapters::MysqlAdapter:0x335e154&gt;
  #&lt;ActiveRecord::ConnectionAdapters::MysqlAdapter:0x335e154&gt;
  #&lt;ActiveRecord::ConnectionAdapters::MysqlAdapter:0x335e154&gt;
  #&lt;ActiveRecord::ConnectionAdapters::MysqlAdapter:0x335e154&gt;
</pre>

<p>Not what we want. Now, there are, most likely, fancier and better ways of doing this, and it seems a little bit sketchy to have to roll one's own connection pool ... but I like things that work and are easy, so:</p>

<pre>
  ActiveRecord::Base.remove_connection
  pool = []
  4.times do |i|
    pool.push(ActiveRecord::Base.establish_connection)
    Process.fork do
      connection = pool[i].connection
      puts connection
      ActiveRecord::Base.remove_connection
    end
  end
  Process.waitall
  ActiveRecord::Base.establish_connection
</pre>

<p>And now we get:</p>

<pre>
  #&lt;ActiveRecord::ConnectionAdapters::MysqlAdapter:0x335ea28&gt;
  #&lt;ActiveRecord::ConnectionAdapters::MysqlAdapter:0x3351ddc&gt;
  #&lt;ActiveRecord::ConnectionAdapters::MysqlAdapter:0x3345140&gt;
  #&lt;ActiveRecord::ConnectionAdapters::MysqlAdapter:0x33384f4&gt;
</pre>

<p>Perfect. And, yes, those <code>connection</code> objects are perfectly good and you can go ahead and call <code>connection.execute</code>, <code>connection.select_value</code>, etc. exactly as you normally would.</p></div>
</content>


    <feedburner:origLink>http://blog.swivel.com/code/2009/08/sharp-threads.html</feedburner:origLink></entry>
    <entry>
        <title>Packaging Dojo with Capistrano</title>
        <link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/typepad/huned/swivelcode/~3/BwnLq41h0Jw/pac.html" />
        <link rel="replies" type="text/html" href="http://blog.swivel.com/code/2009/07/pac.html" thr:count="0" />
        <id>tag:typepad.com,2003:post-6a00d8341c8db453ef0115712c6034970c</id>
        <published>2009-07-21T16:21:18-07:00</published>
        <updated>2009-07-21T16:21:18-07:00</updated>
        <summary>While we love The Dojo Toolkit, we're not sure if it's even possible for one application to use all of its functionality. At Swivel, we use many of dojo's charting components, but not much else. One of our chart pages...</summary>
        <author>
            <name>Ben Walsh</name>
        </author>
        
        
<content type="html" xml:lang="en-US" xml:base="http://blog.swivel.com/code/">
&lt;div xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;p&gt;While we love &lt;a href="http://www.dojotoolkit.org"&gt;The Dojo Toolkit&lt;/a&gt;, we're not sure if it's even possible for one application to use all of its functionality. At Swivel, we use many of dojo's charting components, but not much else. One of our chart pages will pull in several dozen Javascript files as dojo imports the resources it needs at runtime. Surely there has a way of getting all the dojo we need, and nothing else? Well, the Dojo Foundation hivemind has thought of that.&lt;/p&gt;

&lt;h3&gt;63% Extra, Free!&lt;/h3&gt;

&lt;p&gt;Let's put our results above the fold: packaging our dojo files cut the load time for our most dojo-intensive pages by &lt;strong&gt;63%&lt;/strong&gt; on average and dramatically reduced the number of individual requests. The change for one page was as follows:&lt;/p&gt;

&lt;iframe style='width:420px;height:350px;overflow:hidden;' src='https://business.swivel.com/workbooks/3963-Packaging-Dojo.embed?secret=jVbWbmdhK0KSVa27MM7dFA%3D%3D&amp;embed=%7B%22sheetId%22%3A%209355%7D'&gt;&lt;p&gt;Iframe&lt;/p&gt;&lt;/iframe&gt;

&lt;p&gt;There's good documentation for using Dojo's system for &lt;a href="http://www.dojotoolkit.org/book/dojo-book-0-9/part-4-meta-dojo/package-system-and-custom-builds"&gt;packaging custom builds&lt;/a&gt;. You'll need the src build which includes the &lt;code&gt;util&lt;/code&gt; directory -- for our purposes we needed to tweak our &lt;a href="http://wiki.github.com/evilchelu/braid"&gt;&lt;code&gt;.braids&lt;/code&gt; file&lt;/a&gt; to include:&lt;/p&gt;

&lt;pre&gt;
public/javascripts/dojotoolkit/util:
  squashed: true
  url: http://svn.dojotoolkit.org/src/util/trunk
  type: svn
  revision: 18839
  remote: braid/public/javascripts/dojotoolkit/util
&lt;/pre&gt;

&lt;p&gt;(I'll save all the gory details of installing &lt;code&gt;git+svn&lt;/code&gt; to get braid to work locally for another, longer, and more painful post. Word to the wise: you may need the &lt;a href="http://trac.macports.org/browser/trunk/dports/devel/apr-util/Portfile"&gt;apr Portfile&lt;/a&gt;.)&lt;/p&gt;

&lt;p&gt;Selecting the dojo components you need is straightforward enough. Have a look at what dojo files your page is requesting and work from there. Our build profile ended up looking like this:&lt;/p&gt;

&lt;pre&gt;
dependencies = {
  layers:  [{
    name: "swivel_dojo.js",
      dependencies: [
        "dojox.charting.Chart2D",
        "dojox.charting.themes",
        'dojox.gfx.svg',
        'dojox.nls'
      ]
    }
  ],
  prefixes: [
    [ "dijit", "../dijit" ],
    [ "dojox", "../dojox" ]
  ]
};
&lt;/pre&gt;

&lt;p&gt;What we wanted to do, though, was to have the raw dojo files under source control through Braid, and only use the package in production. Debugging the single humongous line of generated Javascript is tricky, for one thing, and managing the versioning of the Dojo toolkit files properly was also important. This required a bit of trickery.&lt;/p&gt;

&lt;h3&gt;Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo&lt;/h3&gt;

&lt;p&gt;We created a &lt;code&gt;dojo_release&lt;/code&gt; directory as a sibling of &lt;code&gt;dojotoolkit&lt;/code&gt;, and added a symbolic link called &lt;code&gt;dojo&lt;/code&gt; that points back up to &lt;code&gt;dojotoolkit&lt;/code&gt;. So &lt;code&gt;public/javascripts/dojo_release/dojo&lt;/code&gt; is a symbolic link to &lt;code&gt;public/javascripts/dojotoolkit&lt;/code&gt;. That's the version that gets checked in to source control, and all files that use our dojo build have this line of Javascript:&lt;/p&gt;

&lt;pre&gt;
 &lt;%= javascript_include_tag('dojo_release/dojo/dojo/dojo', 'dojo_release/dojo/dojo/swivel_dojo', '...' %&gt;
&lt;/pre&gt;

&lt;p&gt;Now everything should work as before, we're just getting to the dojo files in a different way. So anyone checking out the source and working with it will see no difference except the paths for those Javascript files. Or, to put it another way, we haven't really done anything yet.&lt;/p&gt;

&lt;p&gt;What we want the dojo packaging script to do is run against our new profile and output the packaged version into the &lt;code&gt;dojo_release&lt;/code&gt; directory, clobbering the symlink with the compiled package. The best time for this to happen would be after the code is updated via our &lt;code&gt;deploy:update_code&lt;/code&gt; task. And, so, a new task is added to &lt;code&gt;configuration/deploy.rb&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;
  namespace :dojo do
    desc "package dojo files using Swivel profile"
    task :package, :roles =&gt; :db, :only =&gt; { :primary =&gt; true } do
      run &lt;&lt;-SCRIPT
        rm #{release_path}/public/javascripts/dojo_release/dojo &amp;&amp;
        cd #{release_path}/public/javascripts/dojotoolkit/util/buildscripts &amp;&amp;
        ./build.sh profile=swivel action=release releaseDir=../../../dojo_release
      SCRIPT
    end
  end
&lt;/pre&gt;

and

&lt;pre&gt;
    after "deploy:update_code", "deploy:dojo:package"
&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;SCRIPT&lt;/code&gt; heredoc consists of multiple lines chained with &lt;code&gt;&amp;&amp;&lt;/code&gt; because Capistrano will otherwise instantiate a new session for each command. It's important to go to the &lt;code&gt;buildscripts&lt;/code&gt; directory unless you've done some munging of your Java classpaths or whatever it is Java needs, I don't know and I'm not sure I want to know. And, finally, setting the build script's &lt;code&gt;releaseDir&lt;/code&gt; will put the packaged dojo javascript where your existing &lt;code&gt;javascript_include_tag&lt;/code&gt; can find it.&lt;/p&gt;

&lt;p&gt;And that's it. Run &lt;code&gt;cap deploy&lt;/code&gt; and the script should run, packaging all the dojo code it needs into a single (huge!) line of Javascript. When you view your deployed app using a debugger like Firebug or Webkit's built-in developer tools, you'll see how the Javascript files are being served differently. And your users won't need those tools to see the difference.&lt;/p&gt;&lt;/div&gt;
</content>


    <feedburner:origLink>http://blog.swivel.com/code/2009/07/pac.html</feedburner:origLink></entry>
    <entry>
        <title>Rails auto_link and certain query strings</title>
        <link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/typepad/huned/swivelcode/~3/K9X-RBD6x0M/rails-auto_link-and-certain-query-strings.html" />
        <link rel="replies" type="text/html" href="http://blog.swivel.com/code/2009/06/rails-auto_link-and-certain-query-strings.html" thr:count="0" />
        <id>tag:typepad.com,2003:post-67638857</id>
        <published>2009-06-05T10:40:09-07:00</published>
        <updated>2009-06-05T00:38:26-07:00</updated>
        <summary>Our local newspaper, the San Francisco Chronicle, is occasionally a source for data stories posted to Swivel, and that's how we discovered that there are a couple of edge cases that Rails's auto_link doesn't handle perfectly. A typical Chronicle link...</summary>
        <author>
            <name>Ben Walsh</name>
        </author>
        <category scheme="http://www.sixapart.com/ns/types#category" term="rails" />
        
        
<content type="html" xml:lang="en-US" xml:base="http://blog.swivel.com/code/">
&lt;div xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;p&gt;Our local newspaper, the &lt;a href="http://www.sfgate.com"&gt;San Francisco Chronicle&lt;/a&gt;, is occasionally a source for data stories posted to Swivel, and that's how we discovered that there are a couple of edge cases that Rails's &lt;code&gt;auto_link&lt;/code&gt; doesn't handle perfectly.&lt;/p&gt;

&lt;p&gt;A typical Chronicle link looks something like this: &lt;code&gt;&amp;lt;a href="&lt;a href="http://www.sfgate.com/cgi-bin/article.cgi?f=/c/a/2007/08/24/WIJKRIC6E.DTL"&gt;http://www.sfgate.com/cgi-bin/article.cgi?f=/c/a/2007/08/24/WIJKRIC6E.DTL"&lt;/a&gt;&amp;gt;&lt;/code&gt;. Nothing too peculiar there. However, when passed through the &lt;code&gt;auto_link&lt;/code&gt; function, the &lt;code&gt;/&lt;/code&gt; character at the beginning of the value of the query string variable causes the entire value to be dropped, leaving us with lots of links to &lt;code&gt;&amp;lt;a href="&lt;a href="http://www.sfgate.com/cgi-bin/article.cgi?f="&gt;http://www.sfgate.com/cgi-bin/article.cgi?f="&lt;/a&gt;&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This bug has been noted by &lt;a href="http://www.thesatya.com/blog/2009/05/rails_auto_link.html"&gt;Satya&lt;/a&gt; among others, and the monkey-patch solution is fairly straightforward. The first step is to write a functional test:&lt;/p&gt;

&lt;pre&gt;
  test("URL querystring variables can begin with a slash") do
    url = 'www.example.com?url=/rails/cannot/deal/with/this/'
    post(:create, :resource =&gt; { :name =&gt; "test", :link =&gt; url })
    get(:show, :id =&gt; assigns(:resource).id)
    assert_select("a[href=http://#{url}]")
  end
&lt;/pre&gt;

&lt;p&gt;Our test fails. The URL is truncated at the &lt;code&gt;=&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;ActionView's TextHelper includes a regular expression constant &lt;code&gt;AUTO_LINK_RE&lt;/code&gt; which tells Rails how to recognize URLs. We prefer not to tinker with the actual &lt;code&gt;vendor&lt;/code&gt; code itself to avoid any upgrading gotchas or other weirdness, so I copied the relevant RegEx to &lt;code&gt;/configuration/initializers/core_ext.rb&lt;/code&gt;, made the necessary (one-character!) tweak, and overrode the private TextHelper constant with the new Regex. The changed line is in bold:&lt;/p&gt;

&lt;pre&gt;
ActionView::Helpers::TextHelper::AUTO_LINK_RE = %r{
              (                          # leading text
                &lt;\w+.*?&gt;|                # leading HTML tag, or
                [^=!:'"/]|               # leading punctuation, or
                ^                        # beginning of line
              )
              (
                (?:https?://)|           # protocol spec, or
                (?:www\.)                # www.*
              )
              (
                [-\w]+                   # subdomain or domain
                (?:\.[-\w]+)*            # remaining subdomains or domain
                (?::\d+)?                # port
                (?:/(?:[~\w\+@%=\(\)-]|(?:[,.;:'][^\s$]))*)* # path
                &lt;b&gt;(?:\?[\w\+@%&amp;=.;:&lt;b&gt;/&lt;/b&gt;-]+)?     # query string&lt;/b&gt;
                (?:\#[\w\-]*)?           # trailing anchor
              )
              ([[:punct:]]|&lt;|$|)       # trailing text
             }x
&lt;/pre&gt;

&lt;p&gt;Our test passes, and all is well.&lt;/p&gt;&lt;/div&gt;
</content>


    <feedburner:origLink>http://blog.swivel.com/code/2009/06/rails-auto_link-and-certain-query-strings.html</feedburner:origLink></entry>
    <entry>
        <title>capistrano hanging?</title>
        <link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/typepad/huned/swivelcode/~3/eIZUO2olzX4/capistrano-hanging.html" />
        <link rel="replies" type="text/html" href="http://blog.swivel.com/code/2009/05/capistrano-hanging.html" thr:count="0" />
        <id>tag:typepad.com,2003:post-67420603</id>
        <published>2009-05-29T12:22:50-07:00</published>
        <updated>2009-05-29T12:22:50-07:00</updated>
        <summary>I was a lone developer who was trying to deploy to our staging environment, but my capistrano setup would hang. no one else was having a problem. I traced the problem to a hanging ssh, so I wrote up a...</summary>
        <author>
            <name>visnu</name>
        </author>
        
        
<content type="html" xml:lang="en-US" xml:base="http://blog.swivel.com/code/">
&lt;div xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;p&gt;I was a lone developer who was trying to deploy to our staging environment, but my capistrano setup would hang.  no one else was having a problem.  I traced the problem to a hanging ssh, so I wrote up a simple Net::SSH script to try to ssh to the machines:&lt;/p&gt;

&lt;code&gt;&lt;pre&gt;
Net::SSH.start 'web01-s6.stage', 'build' do |ssh
  puts ssh.exec!('ls')
end
&lt;/pre&gt;&lt;/code&gt;

&lt;p&gt;this was working totally fine.  I was baffled.  I then ran cap under rdebug and still noticed that it was hanging when connecting to all the machines.  I then tried duplicating the multithreaded connect:&lt;/p&gt;

&lt;code&gt;&lt;pre&gt;
%w/ daemon01-s6.stage web01-s6.stage /.map do |s|
  Thread.new s do |server|
    connection = Net::SSH.start server, 'build', options
    puts connection.exec!('ls')
  end
end.each { |t| t.join }
&lt;/pre&gt;&lt;/code&gt;

&lt;p&gt;hang!  so, it was threads + Net::SSH that was causing my problem.  I asked around and all the other developers were using ruby 1.8.7p72.  I was at 1.8.7p160 (I upgrade a lot).  so, I downgraded my ruby (good thing I still had the old one deactivated in macports) and huzzah!  no more hangs!  I can deploy again:&lt;/p&gt;

&lt;iframe style='overflow:hidden; width:420px; height:350px;' src='https://business.swivel.com/charts/1770-capistrano-hangs-.embed?secret=&amp;embed=%7B%22fontSize%22%3A%207%7D'&gt;&lt;p&gt;Iframe&lt;/p&gt;&lt;/iframe&gt;&lt;/div&gt;
</content>


    <feedburner:origLink>http://blog.swivel.com/code/2009/05/capistrano-hanging.html</feedburner:origLink></entry>
 
</feed><!-- ph=1 --><!-- nhm:dynamic-ssi -->
