Archived entries for snippets

Easy Syncing of GitHub Pages

I’ve started using GitHub more and more recently as I’m finding Git’s steep learning curve, as compared to SVN, outweighed by GitHub’s usefulness and flexibility. One of those factors is GitHub’s “Pages” feature. From the docs:

The GitHub Pages feature allows you to publish content to the web by simply pushing content to one of your GitHub hosted repositories.

For example, I’ve recently started a repo to begin adding the many miscellaneous tests, POCs and demos I create during the course of development. Instead of requiring someone to download the repo just to see the examples, I use GitHub Pages to host the rendered version (when applicable). The “Mimicking Links” page is the first one I’ve published.

GitHub makes this automatic when you create a branch of your master named gh-pages. Any time you push to gh-pages, the results are published. Easy enough, but I quickly realized that I needed a way to mirror all changes on master in gh-pages without constantly having to type:

git checkout gh-pages
git merge master
git push origin gh-pages
git checkout master

Some quick searching turned up Oli Studholme’s helpful post “GitHub Pages and deleting git’s master branch”. He outlines his own attempts (and suggestions from the comments) and what finally worked for him. Since he had more requirements (deleting the master branch), I wanted to post exactly what I’ve ended on.

First, create your local repo and add it to GitHub.

From the command line, navigate into the root of your repo and run following block of code as referenced in the “Project Pages” section of the GitHub Pages docs (make sure you have no changes waiting to be committed):

git symbolic-ref HEAD refs/heads/gh-pages
rm .git/index
git clean -fdx

Now that your working directory is clean, merge in the master branch and push gh-pages to GitHub:

git merge master
git push origin gh-pages

You can now visit the url http:username.github.com/yourRepo/ to view the results (the first push may take a little time to show your changes).

Now that your pages are in place, you’ll want to automate the merging[1] to gh-pages any changes you commit in master.

To do this, open the post-commit.sample file located in yourRepo/.git/hooks and replace its contents with the following, saving it as post-commit:

#!/bin/sh
# Mirror master in gh-pages
git checkout gh-pages
git merge master
git checkout master

This block will run after every commit you make to the master branch (you’ll see the output on the command line).

All that’s left to do is push both branches to GitHub any time you’ve made a commit:

git push --all

I’m still pretty new to Git/GitHub, so any suggestions or corrections are appreciated.


  1. Oli’s post suggests rebase, but I’m sticking with merge as I understand it better.  ↩

My Alfred Custom Searches

I set up a page to share (and sync) some of the custom searches I use with Alfred. Hopefully they have a plan to create a network for contributing/browsing/filtering other users custom searches (do they?).

Update: They do!.

Command Line Aliases

I’ve been trying to hone my command line skills as it’s sometimes the only way to do complex operations (searching remote svn log files). One of the actions I find most repeated is finding my way into the various directories to perform these operations. My typing skills are less than stellar, so it kind sucks to type (even with tab completion):

cd /Applications/MAMP/htdocs

In looking for a better way to navigate to my repo, I created an alias. This means that instead of typing:

cd /Applications/MAMP/htdocs

I can simply type:

repo

That variable will be “expanded” into the string cd /Applications/MAMP/htdocs and executed by the shell.

Here’s how make this black magic a reality:

OSX (UNIX)
—–
Open Finder and click on your home folder.
Show the hidden files using the keystroke shift + command + . (or use a dashboard widget)
Open the hidden file named “.profile” (or create one with Textedit if it doesn’t exist)
Add the following text (I use MAMP as my server, which is located at /Applications/MAMP/):

alias repo='/Applications/MAMP/htdocs'

Save the file.
Open a new Terminal (/Applications/Utilities/Terminal.app)
Type:

repo

You should now be in the /htdocs directory (or whatever path you set for repo)

Windows
——–
Open Notepad and create a new text file.
Add the following text (I use WAMP as my server, which is located at C:\wamp):

cd C:\wamp\www

Save the file as “repo.bat” in C:\WINDOWS\system32.
Open a Command Prompt at Start->All Programs->Accessories->Command Prompt (or using the Start Menu shortcut r and CMD)
Type:

repo

You should now be in the \www directory (or whatever path you set for repo)

OSX (UNIX) reference

Windows reference

Toggle Class – The jQuery Way vs. The Native Way

I work with a team of developers located in the US, Canada and Bangalore. On behalf of the North American team, I send daily status emails detailing what each dev worked on, as well as their svn commit log, so the offshore devs and project leadership can stay synced.

For the past 2 or 3 weeks I’ve been including little quick tips on CSS and javascript. The team I’m on is composed of people with a variable level of skills and this is an attempt to affect those levels.

I thought I’d start posting some of these to archive ones I would have found helpful when I first started programming.

We use jQuery in our project and the majority of the devs (including myself) learned javascript via jQuery. Below is what it takes to toggle a class using jQuery vs. native javascript. As you can see, we’ve had it easy.

The jQuery Way

$( '.some-class' ).toggleClass( 'newClass' );

The Native Way (I’m sure there are better ways):

var i = 0,
    elements = document.getElementsByClassName('some-class'),
    len = elements.length,
    classToggle = function( element, tclass ) {

        var classes = elements[i].className,
            pattern = new RegExp( tclass );
            hasClass = pattern.test( classes );

        classes = hasClass ? classes.replace( pattern, '' ) : classes + ' ' + tclass;
        elements[i].className = classes.trim();
    };

for ( ; i < len; i++ ) {
    classToggle( elements[i], 'newClass' );
}

The native example could be wrapped up a bit tighter to make it easily reusable. One of the reasons the jQuery example is so concise is that it relies on it's own methods for making collections and performing loops. The $ and toggleClass functions have quite a bit of code backing them up. If I were to add in all of the source code jQuery uses to preform these tasks, things would look a lot different.

But that's not the point. The thing that has enabled me to use jQuery as just one of the tools in my toolbox, instead of the only tool, is understanding the underlying functionality.

A couple of good references: the jQuery source (of course) and the MDC.

Using jQuery’s queue(), dequeue() and delay() Methods

These methods were very confusing to me so I decided to do some demystification and see what the hell was going on. jQuery’s documentation sets them up as methods related to the effects api. By default this is true, but I found this little misleading.

queue() / dequeue(), in short, allows you to create a queue of functions to be executed on the matched element(s) and then execute them in order.

delay() allows you to create a delay between functions in the queue.

None of the functions are run until the dequeue() method is run. This could be a click event, for instance.

Take for instance the following code:

$(document).ready(function() {

	// cache the body element
	var body = $('body');

	/*
	  Create a "bodyQueue" queue for the body element and add a function into it.
	  After this funnction runs it will delay the "bodyQueue" queue by 5 seconds.
          None of the functions are run until an event triggers the dequeue() method.
          This event is defined at the end using a click on the body.
	*/
	body.queue('bodyQueue', function(){ 
	    console.log('1st function. Next one is delayed by 5 seconds');
	    $(this).dequeue('bodyQueue');
	}).delay(5000, 'bodyQueue');

	// Add another
	body.queue('bodyQueue', function(){ 
	    console.log('2nd function (delayed 5 seconds)');
	    $(this).dequeue('bodyQueue');
	});

	// Add another
	body.queue('bodyQueue', function(){ 
	    console.log('3rd function');
	    $(this).dequeue('bodyQueue');			
	});

	// Add another
	body.queue('bodyQueue', function(){ 
	    console.log('4th function');
	    $(this).dequeue('bodyQueue');
	});

	/*
	  Add another and delay the "bodyQueue" queue by 5 seconds.
	*/
	body.queue('bodyQueue', function(){ 
	    console.log('5th function. Next one is delayed by 5 seconds');
	    $(this).dequeue('bodyQueue');
	}).delay(5000, 'bodyQueue');

	// Add the last one
	body.queue('bodyQueue', function(){ 
	    console.log('6th function (delayed 5 seconds)');
	});

	// Show the queued functions when the page loads
	var queue = body.queue('bodyQueue');                               
	console.log('There are ' + queue.length + ' functions left in the "bodyQueue" queue:');
	console.log(body.queue('bodyQueue'));

	// Add an event to fire the "bodyQueue" queue
	body.click(function(){

	    // Run everything in the "bodyQueue" queue
	    body.dequeue('bodyQueue');

	});

});

What I’ve defined here is a queue with the name bodyQueue, attached it to the body element and added a series of functions. When the body element registers a click event, the callback runs body.dequeue('bodyQueue'), firing the queued functions in bodyQueue.

View the demo. Make sure you run it in Firefox with the Firebug console open to view the feedback.

Resources:

jQuery for Designers | API: queue & dequeue

jQuery in Action 2nd edition: Queuing functions for execution

Using the J/K keys for Content Navigation

If anyone has ever been to the Boston Globe’s The Big Picture or FFFFOUND! you may have used your keyboard to navigate through a page’s content. The j (forward) and k (backward) keys use as navigation has started to trickle into modern sites. Even Google’s Gmail uses this convention to navigate between emails.

I wanted to give it a try so I’ve created a sample jQuery plugin (not really all that full-featured) that offers similar functionality as The Big Picture. Try out the demo with some pics of a graffiti-ridden water tower.

The code is pretty straight forward. It simply finds all images inside the given container.

$('#image-wrapper').jkNavigation();

Keeping track of the currentImage variable was a bit tricky so if anyone has any optimizations, let me know.

Tested in Safari 4.0.4 and Firefox 3.5.7.

Download sample plugin

(function($) {
	
	$.fn.extend({
		jkNavigation: function(options) {
			return this.each(function() {
				new $.JKNavigation(this, options);
			});
		}
	});
	
	$.JKNavigation = function(element, options) {
		
		var defaults = {
			// no options at the moment
		};
		this.options		= $.extend({}, defaults, options || {});
		this.element		= $(element);
		this.images			= $('img', this.element);
		this.currentImage	= null;
		this.run();
	};
	
	$.extend($.JKNavigation.prototype, {
		
		run: function() {
			
			self = this;
			
			$(window).bind('keydown', function(event) {
								
				var key = event.keyCode;
				
				switch(key) {
					case 74:
						if(self.currentImage == null) {
							self.currentImage = 0;
						} else if(!(self.currentImage == self.images.length - 1)) {
							self.currentImage++;
						}
						break;
					case 75:
						if(self.currentImage == null) {
							return;
						} else if(!(self.currentImage == 0)) {
							self.currentImage--;
						}
						break;
					default:
					return;
				}
				
				var img = self.images.eq(self.currentImage);
				var pos = img.offset().top;
				
				$('html, body').scrollTop(pos);
				
			});
			
		}
		
	});
	
})(jQuery);

Dot vs. Square Bracket Notation in Javascript

I have been looking for an explanation on this for a while. This article summed it right up, Javascript Square Bracket Notation

Javascript also offers an alternative property accessor notation using square brackets in a way that is similar to the way in which the indexed members of an Array are accessed, except that a string is used between the square brackets. This alternative notation is extremely powerful and useful but gets very little coverage in most books on javascript and that seems to leave novice javascript programmers unaware that they even have this option.

Using square bracket notation you can change this:

document.body;

into this:

document['body'];

More importantly though, you can use variables as function names:

var genericString = 'Hello, my name is Ryan.';

var stringMethod = 'split';

genericString[stringMethod](' ');

// returns the array ["Hello,", "my", "name", "is", "Ryan."]


Copyright © Ryan Fitzer 2010. All rights reserved.

RSS Feed. This blog is proudly powered by Wordpress and uses a modified version of Modern Clix, a theme by Rodrigo Galindez.