I Am Not Myself

Bills.Pay(Developer.Skills).ShouldBeTrue()

Category Archives: Cheez

Useful Tool of the Day: smtp4dev

We send a lot of emails to our users at Cheezburger. Sign up for an account, get a new user email. Submit some funny content, get a message with a link to the content so you can find it. Make the homepage and get a congratulatory message. You get the idea. As you can image our marketing team loves to wordsmith and prettify these messages. So we update them often.

I primarily work out of a Virtual Machine and try to keep running background tasks to a minimum. So, I don’t particularly want a SMTP server running unless I am actively working on email code. Enter smtp4dev, a simple light weight dummy SMTP server. It runs in your system tray and gives you an easy way to capture email messages and view them.

So some simple code like this

using System.Net.Mail;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var message = new MailMessage("dirk@diggler.com", "jack@horner.com")
                {
                    Subject = "I AM THE STAR!",
                    Body = @"You're not the boss of me, Jack. You're not the king
                            of Dirk. I'm the boss of me. I'm the king of me. I'm 
                            Dirk Diggler. I'm the star."
                };

            new SmtpClient("localhost", 25)
                .Send(message);

        }
    }
}

smtp4dev will capture it like this

MvFABVU

You can simply double click the message and open the EML file in your default email application to view it.

Useful jQuery Plugin of the Day: Waypoints

At Cheezburger, my team is currently working on a sharing widget for our recently released list post type. If you take a look at this list, you will see our MVP of the idea. You will notice a share box in the left gutter that appears to float in a fixed position while you scroll through the items in the list giving you the opportunity to share at any point.

We are using an awesome little jQuery plugin called Waypoints to accomplish this. Waypoints makes it easy to execute a function whenever you scroll to an element. Our implementation looks like this.

define(['jquery', 'mods/device', 'libs/waypoints'], function($, device) {
    var f = {};

    f.listen = function () {
        if (device.is.desktop) {
            $('.js-footer').waypoint(f.affix, { offset: '75%' });
        }
        return this;
    };

    f.affix = function (event, direction) {
        event.stopPropagation();
        $('#js-share-menu-wrap').toggleClass('is-fixed');
        return this;
    };

    return f;
});

In this code we are attaching our waypoint to the footer of of the page. When the footer scrolls into the window viewport the affix method gets called. The affix method simply toggles the is fixed class on the share widget. We are also passing in an options object that tells the waypoint to trigger when the footer scrolls passed the point 75% from the top of the viewport.

In our next iteration, we are planning to change the way the share button behaves as you scroll through the list. The idea being when you click the button while it is within the area of the third list item, the image and title used to share the list on Facebook will be the third list items information. So while you scroll though the list we are updating the share buttons shared information.

We have not implemented this functionality yet, but yesterday I did a spike to figure out how we could accomplish it. And once again, Waypoints made the task easy.

define(['jquery', 'mods/device', 'libs/waypoints'], function($, device) {
    var f = {};

    f.listen = function () {
        if (device.is.desktop) {
            $('.actions').waypoint(f.affix, { offset: '75%' });
            $('.list-asset-item').waypoint(f.onSwitch, { offset: $('#js-share-menu-wrap').offset().top });
        }

        return this;
    };

    f.affix = function (event, direction) {
        event.stopPropagation();
        $('#js-share-menu-wrap').toggleClass('is-fixed');
        return this;
    };

    f.onSwitch = function(event, direction) {
        var item = $(this);
        console.log(direction);
        console.log(item.index());
        console.log($('h2.title', item).text());
        console.log($('div.post-description', item).text());
    };

    return f;
});

In this code I am attaching a waypoint to each list asset item. But this time I am setting the offset to the fixed pixel position of the top of the share widget. This allows me to trigger the onSwitch function as the top of the list asset item crosses the top of the share widget. The handler is scoped correctly for the list asset item so I can easily grab it’s index, title and description. Waypoints will even tell me which direction the user is scrolling.

Here is a quick video showing this code in action.

Why Most Solutions to Gilded Rose Miss The Bigger Picture

EdTjP

A couple years ago, I had the pleasure to work with one of the best teams I have ever and probably will ever get to work with again. There was a certain amount of magic we had over the span of a few months that I will probably be chasing the rest of my professional life. I still have links to the members of that team on my blog titled “Team Awesome”, even though I have long sense moved on and so have many of them.

One of the things that made this team so spectacular was the constant dedication to learning and helping to make each other better. We even had management’s buy off and encouragement which is a rare golden egg. They let us get away with a lot in the name of learning.

At one point we started having team competitions around Code Katas. One member would present a Kata and the other team members would have a week to come up with their best implementations. The presenting member would then publicly critique the implementations and pick a winner. This critique was really cool because you learned a lot about what the presenter considered important and how they thought about problems.

One of these little competitions lead to Terry Huges presenting The Gilded Rose Kata. He actually wrote it himself while he was deep into his infatuation with World of Warcraft. I loved it so much I blogged about it and even put up a starter project on github. The basic gist of the kata is this: Here is a piece of crappy legacy code that works. Along with it goes a textural description of what the code does, some modifications the customer wishes you to implement and some constrains you need to adhere to.

I also posted it to the Software Craftsmanship mailing list, a popular programming meme that I was infatuated with at the time. They went gaga for it. Todd Sedano at Carnegie Mellon University used it in his craftsmanship course. And most receiently, Emily Bache included it in her book The Coding Dojo Handbook.

A couple of things that gnawed at me about the proliferation and spread of the kata where that most of the early commenters credited me as the author, which seems to be mostly resolved with most modern references to the kata. To be clear, it was all Terry. I just really liked the concept.

I was also bugged by all the ports of the kata into different programming languages. The original was done in C#, using the most basic console program structure. Within a week there were Java, Ruby, JavaScript and Python versions. Currently you can find C, C++, SmallTalk.. pretty much any language you would care to do the kata in. I have not seen one in Lua, but it would not surprise me in the slightest. Just hit github and search for Gilded Rose and you will find what you are looking for.

I found this ironic considering the kata is about inheriting someone else’s code and having to implement new features while ensuring that you do not break existing features. The obvious choice to accomplish this is to reimplement in another language.

Imagine you having a conversation with a client that goes some thing like this.

Client: I have this system that a developer who is no longer here wrote a couple years back. The system has been running solid for a long time, but I would like to make a couple modifications. These modifications should be pretty simple. Can you give me an estimate on what you think it would take to implement them?

Programmer: Sure! This is totally doable. The first thing we need to do is rewrite the entire app in another language.

Client: … Really? That seems a bit redundant.

Programmer: Next up we will need to recreate our production environment to support running the new languages platform. Oh and we better migrate all of our data to a new Database platform as well.

Client: .. But how does that help with implementing the new features? This application has run for several years on the existing hardware costing me next to nothing.

Programmer: Oh and now that I think about it we will need to fire all our production support staff and hire new people who understand the new hardware, OS and database infrastructure.

Client:

Programmer: After all that, it will be a breeze to implement these new features.

Now I realize that katas are meant to be simple problem solving exercises that allow you to practice your skills. But I would suggest that one of the skills you should be practicing is entering an unfamiliar environment and being productive quickly. I would like to challenge the kata community to attempt the original kata. See what it is like to live in somebody else’s shoes and be productive.

If you can’t bring yourself to taint your machine with a .NET environment, give it a shot with Mono it runs fine. Or you could pick some other programming environment that you are less than familiar with, there are certainly enough ports of the original. 😉

Getting Started Managing Client Side Scripts with Require.js

Back in the 90s when I started my development career, the first language I learned was Javascript. It is a deeply and perfectly flawed language. We created huge DHTML messes with it. And I moved on to server side development and got lost in .NET for a while. It all kind of left me with the following feeling.

With the rise of jQuery and other frameworks like it, javascript has come back front and center for me. As time goes by, I find I am doing more and more javascript daily. In fact, at Cheezburger javascript is about 80% of my day now. jQuery removes some of the browser compatibility burdens we felt way back in the 90s. And over the course of the last few years I have created a few jQuery messes.

Those messes look a little something like this.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Getting Started with Require.js</title>
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
		<script type="text/javascript">
			$(function(){
				var cfg = $.parseJSON($('#config').html());
				if(cfg.isProduction)
					$('h1').css('background-color', 'red');
			});
		</script>
	</head>
	<body>
		<h1>Sample Application</h1>

		<p>This is a sample application used in a blog post to demonstrate 
			how to get started with <a target="_blank" href="http://requirejs.org">require.js</a>.</p>

		<script id="config" type="application/json">
			{
				"isProduction": true
			}
		</script>
	</body>
</html>

This is a very simplified example, but it is pretty representative of what I used to do. The server has rendered some client side configuration information into an application/json script tag. In the head of the document we have a script tag to include the minified jquery library from the Google CDN. There is also a script block that uses the jquery ready function to read the configuration information and modify the mark up based on a setting.

One problem presented here is the nature in which browsers load javascript. Script tags are blocking operations. Meaning when the browser hits a script tag the script must be downloaded and fully evaluated before continuing. This is why some developers have adopted the convention of putting script tags and blocks at the end of the document body. This way all the mark up is rendered and then scripts start to load and execute.

Now imagine this sample also used about twenty jquery plugins. All those plugins have to load in a blocking fashion and all of them must be in the right order in the markup to satisfy dependencies. And every member of my team must be aware of those dependencies as well and care and feed them. Additionally every script must load before we can fire off any functionality. Are you beginning to understand why some sites are so damn slow to render?

Finally, with this example there is no concept of modularity. I simply open up a ready function and start pluggin away. Grabbing data directly from its source and poking at the dom directly. Abstractions were not my thing apparently, running with scissors as close to the metal as possible seems more accurate.

When I started at Cheezburger, I was introduced to require.js by Matt Mirande. Matt has become my personal javascript savior. He sat me down and we had a come to black baby jesus talk and I am a better man for it.

The best way I can describe require.js is IoC for javascript. If you are not familiar with IoC, please get thy self to the Castle project and do some learnin. Require.js allows you to think about your javascript in terms of discreet modules of functionality. It manages loading those modules asynchronously and executes them as their dependencies are satisfied.

I think the best way to describe require.js might be to simply demonstrate it by converting my example. To start, simply download the require.js library from the site and put it in the root of your scripts directory. Then add a reference to it. The final markup looks like this.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Getting Started with Require.js</title>
		<script type="text/javascript" src="scripts/require.js"></script>		
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
		<script type="text/javascript">
			$(function(){
				var cfg = $.parseJSON($('#config').html());
				if(cfg.isProduction)
					$('h1').css('background-color', 'red');
			});
		</script>
	</head>
	<body>
		<h1>Sample Application</h1>

		<p>This is a sample application used in a blog post to demonstrate 
			how to get started with <a target="_blank" href="http://requirejs.org">require.js</a>.</p>
                
                <ol id="status">
			<li>loading...</li>
		</ol>

		<script id="config" type="application/json">
			{
				"isProduction": true
			}
		</script>
	</body>
</html>

Note that I added an ordered list to the markup. I will be using it to demonstrate the load order of various things I am about to show you. Next, we need to tell require.js what to do. Create a javascript file right next to require called main.js. this will be the main entry point for our require context. The contents of this file looks like this.

require([], function(){
	 var status = document.getElementById('status');
	 var item = document.createElement('li');
	 item.innerText = "main loaded";
	 status.appendChild(item);
});

We then need to change our reference to the require.js script to use our new main entry point script. Simply add a data-main attribute to the script reference like so. You can drop the .js off the end of your file name and the path is relative to the require.js file.

<script type="text/javascript" src="scripts/require.js" data-main="scripts/main"></script>

This script calls the require function passing in an array of dependencies and a function to call when the dependencies have been loaded and executed. Right now I don’t have any dependencies, so I pass an empty array. The function simply uses some straight DOM manipulation to add a list item to my status list.

All this DOM manipulation is silly, considering I have already established the use of jquery. So I am going to fix that up by making jquery my first dependency. jQuery is special as a dependency because I still want to load it from the CDN and it is not a proper AMD module. No problem require.js can handle that.

require.config({paths: { jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min' }});

require(['jquery'],function($){
	$('<li>main loaded</li>').appendTo('#status');
});

Using the config method of require, I can set the path that jquery should be loaded from. I only need to do this once in the main entry point script. All other modules can simply add a dependency to jquery and not worry about it.

My require statement has changed a little bit. I have explicitly added jquery as a dependency and pass a reference to it in my callback function. At this point I am free to use jquery as I see fit. jQuery plugins will work the same way. If you are loading them from a CDN, set the path and simply add them to the dependency list. if you don’t need to interact with the plugin directly, you can drop the reference to the function.

require(['jquery','plugin-with-methods', 'just-needs-to-load'],function($, plugin){
	plugin.dosomethingwith($);
});

Note that by convention libraries that simply need to load should be at the end of the dependency chain to not cause issues with the function call.

We can now safely remove the reference to jquery from our markup and migrate our ready function into the body of our main.js require call.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Getting Started with Require.js</title>
		<script type="text/javascript" src="scripts/require.js" data-main="scripts/main"></script>
	</head>
	<body>
		<h1>Sample Application</h1>

		<p>This is a sample application used in a blog post to demonstrate 
			how to get started with <a target="_blank" href="http://requirejs.org">require.js</a>.</p>

		<ol id="status">
			<li>loading...</li>
		</ol>

		<script id="config" type="application/json">
			{
				"isProduction": true
			}
		</script>
	</body>
</html>
require.config({paths: { jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min' }});

require(['jquery'],function($){
	$('<li>main loaded</li>').appendTo('#status');

	var cfg = $.parseJSON($('#config').html());
	if(cfg.isProduction)
            $('h1').css('background-color', 'red');
});

We have now successfully set up require.js and modified our use of jquery so that it is treated like any other require module. I can now start breaking out useful functionality into reusable modules. It seems like configuration is a pretty obvious module. Lots of other modules will want to use the configuration object and knowing how to read it out of the markup seems like a SRP violation.

I’ll start by creating a mods folder in my scripts folder to hold all my modules. Then create a configuration.js file in it. To define a module you call the define method, pass in your dependencies as an array and a function.

define(['jquery'], function($){
	$('<li>configuration loaded</li>').appendTo('#status');
});

This module simply appends a meesage to our status list that it has been loaded. Let’s modify our main.js to depend on this module.

require(['jquery', 'mods/configuration'],function($, configuration){
	$('<li>main loaded</li>').appendTo('#status');

	var cfg = $.parseJSON($('#config').html());
				if(cfg.isProduction)
					$('h1').css('background-color', 'red');
});

All I need to do is add the relative path of the configuration module to the dependencies list and add a reference to it in the callback function signature. Executing this code right now yields the following output in our status list.

  1. Loading…
  2. configuration loaded
  3. main loaded

Note that the configuration module is loaded and executed first. Then the main entry point is executed. This chain of dependencies is figured out by require.js. Now let’s flesh out our configuration module.

define(['jquery'], function($){
		
	var module = {};

	module.getConfig = function(){
		return $.parseJSON($('#config').html());
	};

	$('<li>configuration loaded</li>').appendTo('#status');
	return module;
});

And finally, modify our main.js to consume the new module.

require(['jquery', 'mods/configuration'], function($, cfg) {
	$('<li>main loaded</li>').appendTo('#status');

	if(cfg.getConfig().isProduction)
		$('h1').css('background-color', 'red');
});

Now our consuming code has no knowledge of how the configuration is retrieved, it just uses the values. We can feel free to refactor the configuration module without effecting consumers at all. Lets do that and add some caching so we are not reading the DOM every time we get the configuration.

define(['jquery'], function($){
		
	var config, module = {};

	module.getConfig = function(){
		return config || (config = $.parseJSON($('#config').html()) || {});
	};

	$('<li>configuration loaded</li>').appendTo('#status');
	return module;
});

Bam, application keeps on humming. Nice. Now admittedly this example is pretty contrived. But I hope the point was delivered and you could follow all the moving parts. If you are interested in trying it out the project is up on github. Why not try implementing a module to handle our little status logging implementation?

Update: Here are some comments I got from Mr. Mirande on this post. I thought my readers might be interested in hearing the critique of this article from my javascript mentor.

First off, wow, totally honored / humbled by the shout-out dude! So awesome – Thanks! 🙂 Second, great post sir! Was a fun and fast read which managed to pack almost all the key points into a nice, digestible nugget. Couple things I noticed… and in general these point to main flaw in the whole AMD thing: things can get a bit fiddly / WTF-y once you get past the initial setup… and, well, initial setup itself is kind of a pain 🙂

1: “jQuery… is not a proper AMD module” – well, it kind of is. It’s just making use of a feature of AMD that is usually best avoided – named modules. For almost every use-case, you want to go with “anonymous” modules as they are easier to move around and require less boilerplate. We do actually use named modules during testing (via our testing.js thinger (testing.req.using() ) this is how we stub out dependencies at the module level.

2: jQuery plugins – This is trickier… basically only AMD modules (shim’ed or otherwise) can be executed in a specific order. Normal, non-AMD, scripts will be load and executed immediately. So, in your example where you load jQuery as a module and a jQuery plugin as a script, there’s a chance the plugin will load before jQuery itself and throw an error. >_< In require 2.x, they added the concept of a “shim” to better accommodate scenarios where devs are working with both AMD and non-AMD resources. Again, shit gets fiddly 😦 so I’ve always just wrapped plugins such that they operate either as AMD modules or standard browser globals. Neither approach is really friendly to folks just getting started unfortunately.

3: Module return values – I like how you describe the ordering of dependencies in the define() / require() callback functions but you might want to be more specific in describing the module mechanic (e.g. explicitly returning something vs. not). Personally, I found this to be the key revelation when working with AMD – each module offers it’s own “sandbox” of sorts – a new scope where you don’t have to worry about name collisions, can specify public / private things, etc.

Anyway, I don’t think these are major omissions… it’s really tricky to find the right level of detail when explaining AMD to newbs and I think you’ve pretty much nailed it… but I figured I’d point them out in case they are helpful.

Implementing Asynchronous Actions Based On User Preferences Client Side

On my current project, we needed a way to check a user set preference before taking action on behalf of the user. To be specific, we wanted to check if the user prefers for us to post an open graph action to facebook when they favorite a meme on our site. The trick is the user preferences are stored in our profile database and all of our open graph work is purely client side.

In our open graph module, we really didn’t want to care how the user preferences were stored. We simply wanted to consume them in a clean way. An example looks like this:

f.onFavorite = function (postUrl) {
        var options = {
            data: postUrl,
            allowed: function(postUrl){
                f.postFavorite(postUrl);
            },
            unknown: function(postUrl){
                $('#js-og-enable-favorite-btn').data('postUrl', postUrl);
                $('#js-og-favorite-gate').modal("show");
            }
        };
        preferences.userPrefers('favoriting', options );
    };

This is the click handler for a favorite button. We pass in the url to the meme the user favorited and construct an options object. The options object defines data associated with the preference as well as a function to perform if the user allows the action. We also include a function to execute if the preference is not currently set. This way we can prompt the user to make a preference. Finally, we call the preferences module with the preference in question and the options.

Deep in the bowels of our preferences module, is the userPrefers method. It looks like this.

f.userPrefers = function(preferenceName, options){
         f.withCurrentPreferences(function(preferences){
         if(preferences[preferenceName])
            options.allowed(options.data);

         if(preferences[preferenceName] == null)
            options.unknown(options.data);
        });
    };

This function calls withCurrentPreferences and passes in a function describing what to do with a set of current preferences. We check to see if the preference we are checking is enabled and call the allowed method passing along the data if it is. Finally, it check is the preference is explicitly null and calls the unknown method if it is.

So far fairly clear and concise. But what magic is this withCurrentPreferences method?

f.withCurrentPreferences = function(action){
        var preferences = f.getPreferencesCookie();
        if(preferences)
            action(preferences);
        else
            f.getPreferences(action);
    };

f.getPreferences = function(action) {
        $.ajax({
            dataType: "jsonp",
            url: cfg.ProfileDomain + '/' + cfg.Username + '/Preferences',
            success: function(preferences){
                f.setPreferencesCookie(preferences);
                if(action)
                    action(preferences);
            }
        });
    };

The method takes an action to execute with preferences and attempts to read a locally stored preference cookie. We cache preferences locally to not bombard our app servers with unneeded calls. If the cookie based preference exists, we simply call the action passing along the preference. If not, we call getPreferences passing along the action. Finally the getPreferences function makes a ajax call out to our app server to get the preferences. On success it saves a preference cookie and if an action was passed in it calls it.

And there you have it a nice clean asynchronous method of taking actions based on a users preference that is managed completely client side and it uses a local caching mechanism to make it zippy.

Here is the full source of the AMD module.

define(['jquery', 'mods/ono-config', 'mods/utils/utils'], function ($, config, cookieJar) {
    var cfg = config.getConfig();
    var f = {};

    f.getPreferences = function(action) {
        $.ajax({
            dataType: "jsonp",
            url: cfg.ProfileDomain + '/' + cfg.Username + '/Preferences',
            success: function(preferences){
                f.setPreferencesCookie(preferences);
                if(action)
                    action(preferences);
            }
        });
    };

    f.setPreferencesCookie = function (preferences) {
       cookieJar.destroyCookie('preferences', cfg.CookieHostname);
       cookieJar.setCookie('preferences', JSON.stringify(preferences), 1000, cfg.CookieHostname);
    };

    f.getPreferencesCookie = function(){
      return JSON.parse(cookieJar.getCookie('preferences'));
    };

    f.userPrefers = function(preferenceName, options){
         f.withCurrentPreferences(function(preferences){
         if(preferences[preferenceName])
            options.allowed(options.data);

         if(preferences[preferenceName] == null)
            options.unknown(options.data);
        });
    };

    f.withCurrentPreferences = function(action){
        var preferences = f.getPreferencesCookie();
        if(preferences)
            action(preferences);
        else
            f.getPreferences(action);
    };

    f.savePreference = function(preferenceName, value){
        f.withCurrentPreferences(function(preferences){
            preferences[preferenceName] = value;
            f.setPreferencesCookie(preferences);
            f.setPreference(preferenceName, value);
        });
    };
    
    f.setPreference = function (preferenceName, value) {
        $.ajax({
            dataType: "jsonp",
            url: cfg.ProfileDomain + '/' + cfg.Username + '/SetPreference',
            data: {
                preferenceToSet:preferenceName,
                preferenceValue: value
            }
        });    
    };
    
    return f;
});