From 5ca4f257ad6e8ae9e6f7435f95e89471ddfcdbfd Mon Sep 17 00:00:00 2001 From: Lee Mallabone Date: Tue, 7 Feb 2012 14:18:23 -0800 Subject: [PATCH] =?UTF-8?q?Make=20the=20name=20(from=20the=20DOM)=20show?= =?UTF-8?q?=20up=20in=20loading=20sidebars=20on=20compose=20forms=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ie. when loading a conversation with a draft open. --- public/javascripts/underscore_extensions.js | 19 ++++++++++++ .../lib/underscore_extensions_spec.js | 29 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/public/javascripts/underscore_extensions.js b/public/javascripts/underscore_extensions.js index c5d2d72..f02ce18 100644 --- a/public/javascripts/underscore_extensions.js +++ b/public/javascripts/underscore_extensions.js @@ -174,6 +174,25 @@ return _.extractEmails(input)[0] || null; }, + // Takes a string that may contain a name, email address and arbitrary punctuation, + // and tries to return a sanitized version of just the name. + nameFromEmail: function (input) { + if (!input) { + return null; + } + if (input.indexOf('@') > -1 && input.indexOf('<') === -1) { + return null; // an email address only, no name present + } + input = input.replace(/<.+$/, '').replace(/\W{2,}/g, '').trim(). + replace(/^\W+/, '').replace(/\W+$/, '').trim(); + + // If there are email-address like things in the remainder, bail + if (input.indexOf('@') > -1) { + return null; + } + return input || null; + }, + // Return a list of all (cleaned) email addresses in a string. extractEmails: function (input) { return _((input || "").split(_.RE_EMAIL)) diff --git a/spec/javascripts/lib/underscore_extensions_spec.js b/spec/javascripts/lib/underscore_extensions_spec.js index 4b4795f..9ecd434 100644 --- a/spec/javascripts/lib/underscore_extensions_spec.js +++ b/spec/javascripts/lib/underscore_extensions_spec.js @@ -98,4 +98,33 @@ describe("_.", function () { }); }); }); + + describe("nameFromEmail", function () { + it("should return a name from a name-email address string", function () { + expect(_('Lee Mallabone ').nameFromEmail()).toBe('Lee Mallabone'); + }); + + it("should handle quotes", function () { + expect(_('"Lee Mallabone" ').nameFromEmail()).toBe('Lee Mallabone'); + }); + + it("should sanitize in the face of dubious punctuation", function () { + expect(_(' "Lee" - , ').nameFromEmail()).toBe('Lee'); + }); + + it("should return null if a name can't be determined", function () { + var cases = [ + 'foo@bar.com', + '"" ', + '', + 'foo@bar.com ', + 'lee@rapportive.com ', + '"lee@localhost" ' + ]; + + _(cases).each(function (email) { + expect(_(email).nameFromEmail()).toBeNull(); + }); + }); + }); });