<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>A JavaScript and Regex centric blog</description><title>Integralist</title><generator>Tumblr (3.0; @integralist)</generator><link>http://integralist.co.uk/</link><item><title>Beginners guide on how to test your code (using Jasmine BDD)</title><description>&lt;ul&gt;&lt;li&gt;Introduction&lt;/li&gt;
&lt;li&gt;Start how you mean to go on&lt;/li&gt;
&lt;li&gt;The ‘write test first’ process&lt;/li&gt;
&lt;li&gt;Other aspects of TDD/BDD&lt;/li&gt;
&lt;li&gt;Using Jasmine&lt;/li&gt;
&lt;li&gt;An example&lt;/li&gt;
&lt;li&gt;Review of example&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ul&gt;&lt;!-- more --&gt;&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Any programmer worth a damn will tell you that you need to test your code. The way this is done is by using ‘unit-tests’.&lt;/p&gt;
&lt;p&gt;The principle is that you write a test for a piece of your applications code and see if it passes.&lt;/p&gt;
&lt;p&gt;Within a test you write a number of ‘assertions’ (which means you’re expecting certain values to be returned at that point in a certain format or type) and if the code fails to produce the relevant value the assertion will fail and thus the test itself will fail.&lt;/p&gt;
&lt;p&gt;There are different methodologies for testing your code, the two most famous are Test-Driven Development (TDD) and Behaviour-Driven Development (BDD). Both are very similar and differ in perspective/terminology more than anything but I won’t get into that here because you’ll just end up getting confused.&lt;/p&gt;
&lt;h2&gt;Start how you mean to go on&lt;/h2&gt;
&lt;p&gt;Something else you normally hear from the TDD crowd is that you *should* write your tests first! That’s probably going to sound a bit alien to you because how can you write tests for code that doesn’t yet exist? Why would anyone do that?&lt;/p&gt;
&lt;p&gt;Well, the reasoning behind it is quite logical when you think about it. Normally you’ll just start writing some code with no idea of how it should work, you just start hacking away and as you progress you go back and refactor sections and make it cleaner/more efficient and hopefully at the end you don’t need to change your code in any meaningful way to appease your users who may be using your code (e.g. if you’re building the next big JavaScript framework then your API is what your users will be relying on and if you discover there is a bug in your code and it means you have to go back and change the API because of it then that causes big concerns for your users).&lt;/p&gt;
&lt;p&gt;So the idea of writing tests first is that you’re thinking about your API from the beginning. You’ll think about what the perfect API is for your code to produce and you’ll ensure you write code that fits that API (you won’t realise halfway through coding “ah crap, this doesn’t work as well as I had hoped it would, I’m going to have to change this”).&lt;/p&gt;
&lt;p&gt;Although we’re not worrying about “writing tests first” in this article, I mention it so you are at least aware of the process.&lt;/p&gt;
&lt;h2&gt;The ‘write test first’ process&lt;/h2&gt;
&lt;p&gt;For those interested it goes a little like this:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;Write a unit-test&lt;/li&gt;
&lt;li&gt;Run the test (it will obviously fail because there is no code for it to run against!)&lt;/li&gt;
&lt;li&gt;Write the smallest amount of code for the unit-test to pass (we’re talking quick and dirty code here)&lt;/li&gt;
&lt;li&gt;Run the test again and watch it pass&lt;/li&gt;
&lt;li&gt;Once the test passes, go back and refactor your code so it’s how it should be (i.e. clean/efficient)&lt;/li&gt;
&lt;li&gt;Run the test again and watch it pass&lt;/li&gt;
&lt;/ul&gt;&lt;h2&gt;Other aspects of TDD/BDD&lt;/h2&gt;
&lt;p&gt;Here are a few other aspects of unit-testing worth mentioning before we get stuck into some examples: methods such as ‘setUp’ and ‘tearDown’ (which run before and after each test) are useful (for example…) because it means you can prepare each test to run from a fresh set-up.  This probably doesn’t make a lot of sense at the moment so I’ll demonstrate this later in our example code below, but trust me, when you’re testing your code it’s useful before each test (or after each test) to reset your environment.&lt;/p&gt;
&lt;p&gt;There are also more complicated aspects such as mocks, stubs and spies which are useful when you start getting deep into unit-testing application code where ‘state’ becomes relevant (e.g. using some of these features makes testing code in the deepest parts of your application a lot easier).&lt;/p&gt;
&lt;p&gt;So with all this in mind, I would highly recommend you go and read a book titled ‘Test-Driven JavaScript Development’ by Christian Johansen (&lt;a href="http://twitter.com/cjno"&gt;@cjno&lt;/a&gt;) which covers all these topics in great detail.&lt;/p&gt;
&lt;h2&gt;Using Jasmine&lt;/h2&gt;
&lt;p&gt;Now, we’re going to be using a BDD library called Jasmine to help run our tests. You can download it from here: &lt;a href="http://pivotal.github.com/jasmine/"&gt;&lt;a href="http://pivotal.github.com/jasmine/"&gt;http://pivotal.github.com/jasmine/&lt;/a&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The set-up is as follows:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;Create an HTML page&lt;/li&gt;
&lt;li&gt;In this page insert the provided css file ‘jasmine.css’ + the two provided js files ‘jasmine.js’, ‘jasmine-html.js’&lt;/li&gt;
&lt;li&gt;Then include your own JavaScript code ‘my-cool-library.js’&lt;/li&gt;
&lt;li&gt;Then include your own ‘my-tests.js’&lt;/li&gt;
&lt;li&gt;After that have an inline script which executes the Jasmine test runner…&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;jasmine.getEnv().addReporter(new jasmine.TrivialReporter());
jasmine.getEnv().execute();&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Within your own ‘my-tests.js’ file is where you’ll write your unit-tests.&lt;/p&gt;
&lt;p&gt;Different unit-testing libraries have different API’s. Jasmine’s API is as follows…&lt;/p&gt;
&lt;pre&gt;describe('test suite name', function(){
	// assertions for your code to try and pass
	// if any assertions fail then this entire suite fails
});
&lt;/pre&gt;
&lt;h2&gt;An example&lt;/h2&gt;
&lt;p&gt;So now imagine your ‘my-cool-library.js’ consisted of an object whose API let the user add/remove or check for CSS classes on an element. Lets say the API was as follows…&lt;/p&gt;
&lt;pre&gt;var header = document.getElementById('my-header');
css.add(header, 'newclass') // --&gt; adds the class 'newclass' to the specified element 'header'
css.has(header, 'newclass') // --&gt; returns a boolean value (true/false) depending on whether the class 'newclass' is found
css.remove(header, 'newclass') // --&gt; removes the class 'newclass' from the specified element 'header'
css.classes(header) // --&gt; returns an Array of classes found on this element
&lt;/pre&gt;
&lt;p&gt;Your test suite for this code could look something like (don’t worry, we’ll discuss after)…&lt;/p&gt;
&lt;pre&gt;// Test Suite
describe('CSS tests', function() {
	
	var header = document.getElementById('my-header');
	
	beforeEach(function() {
		// Reset the className before each spec is run
		header.className = 'myclassa myclassb';
	});
	
	// Spec
	it('should return an Array of class names', function() {
		expect(css.classes(header)).toEqual(['myclassa', 'myclassb']);
		expect(css.classes(header).length).toBe(2);
	});
	
	// Spec
	it('should add class to element', function() {
		css.add(header, 'newclass');
		expect(header.className).toBe('myclassa myclassb newclass');
	});
	
	// Spec
	it('should return a boolean for whether the class is on the given element', function() {
		expect(css.has(header, 'myclassa')).toBeTruthy();
		expect(css.has(header, 'newclass')).toBeFalsy(); // although in the previous spec we added 'newclass' to the element, in this spec this assertion should return false because the beforeEach method above has reset the class list back to 'myclassa myclassb'
	});
	
	// Spec
	it('should remove class from element', function() {
		css.remove(header, 'myclassb');
		expect(header.className).toBe('myclassa');
	});
	
});
&lt;/pre&gt;
&lt;p&gt;…so a few things you’ll notice:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;We’ve grouped all our tests related to the CSS part of our code using Jasmine’s&lt;br/&gt;&lt;code&gt;&lt;br/&gt;describe('test suite name', function(){ /* tests */ });&lt;br/&gt; &lt;/code&gt;&lt;/li&gt;
&lt;li&gt;We’re using a setUp method (which Jasmine calls ‘beforeEach’) to run some code to reset the class names before each test run (so we start from a clean slate for each test) - there is also a corresponding tearDown method which Jasmine calls ‘afterEach’ (see documentation)&lt;/li&gt;
&lt;li&gt;Each test is represented by&lt;br/&gt;&lt;code&gt;&lt;br/&gt;it('expectation of this test', function(){ /* assertions */ });&lt;br/&gt; &lt;/code&gt;&lt;/li&gt;
&lt;li&gt;The assertions are handled by Jasmine’s &lt;code&gt;expect(&lt;em&gt;expressions&lt;/em&gt;).&lt;em&gt;matcher&lt;/em&gt;&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;The assertions method ‘expect’ takes an expression (e.g. some code to execute) and then the result of that code is passed to the ‘matcher’. Our tests consisted of a few matchers such as:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;toEqual()&lt;/li&gt;
&lt;li&gt;toBe()&lt;/li&gt;
&lt;li&gt;toBeTruthy()&lt;/li&gt;
&lt;li&gt;toBeFalsey()&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Jasmine has a few more matchers which you can read more about in the documentation: &lt;a href="https://github.com/pivotal/jasmine/wiki/Matchers"&gt;&lt;a href="https://github.com/pivotal/jasmine/wiki/Matchers"&gt;https://github.com/pivotal/jasmine/wiki/Matchers&lt;/a&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;You can even create your own matchers…&lt;/p&gt;
&lt;pre&gt;// Add our two new matchers. One to check if an object is an Array and the other to check if the result is a Number
// You create these within the beforeEach method which is executed before each test is run
beforeEach(function() {
	this.addMatchers({
		toBeArray: function(expected) {
			return Object.prototype.toString.call(this.actual); === '[object Array]' ? true : false;
		}
	});
	
	this.addMatchers({
		toBeNumber: function(expected) {
			return /\d+/.test(this.actual);
		}
	});
});
&lt;/pre&gt;
&lt;h2&gt;Review of example&lt;/h2&gt;
&lt;p&gt;We’ll look at one of the example tests and explain what’s happening so you get an idea of how Jasmine works, then from there you should be at least good to go in getting up and running and playing around with it yourself.&lt;/p&gt;
&lt;p&gt;I’ve set-up an example of the code found in this post on Github: &lt;a href="https://github.com/Integralist/Unit-testing-with-Jasmine-BDD"&gt;&lt;a href="https://github.com/Integralist/Unit-testing-with-Jasmine-BDD"&gt;https://github.com/Integralist/Unit-testing-with-Jasmine-BDD&lt;/a&gt;&lt;/a&gt; (which should also help you getting started)&lt;/p&gt;
&lt;p&gt;So lets look at one of the tests…&lt;/p&gt;
&lt;pre&gt;it('should add class to element', function() {
	css.add(header, 'newclass');
	expect(header.className).toBe('myclassa myclassb newclass');
});
&lt;/pre&gt;
&lt;p&gt;…as you can see the test starts by describing what is expected of it. In this case it should add a class to the specified element.&lt;/p&gt;
&lt;p&gt;Within the execution of the test itself we can see that we’re executing the css.add() method and telling it to add the class ‘newclass’ to the element ‘header’ (which as you can see in the full code above was an element with an id of ‘my-header’ stored in the variable ‘header’).&lt;/p&gt;
&lt;p&gt;After that code has executed we’re expecting the header element’s className value to be ‘myclassa myclassb newclass’.&lt;/p&gt;
&lt;p&gt;If we were to run the test-runner.html file we should see all tests pass (this is demonstrated by the green bar and the message of ‘4 specs, 0 failure’).&lt;/p&gt;
&lt;p&gt;To see the test suite fail then just amend one of the tests slightly to cause it to fail. For example in the above example we looked at change it to: toBe(‘x myclassa myclassb newclass’) and this will cause the test to fail because obviously the list of class names on the header element is not going to include the class name ‘x’ at the start.&lt;/p&gt;
&lt;p&gt;When you run the test-runner.html’ file now (remember that now one of the tests will fail) you’ll see that instead of a nice clean green bar to highlight success you see a red bar and a drill down into the issue. If you do as I suggested above to cause the test to fail you’ll notice now Jasmine highlights exactly what the problem is to you…&lt;/p&gt;
&lt;p&gt;&lt;img align="middle" alt="Example of failed test suite" src="http://cl.ly/1z3b1g3U1z0e2r2U2c2H/Screen%20Shot%202011-12-31%20at%2013.06.32.png"/&gt;&lt;/p&gt;
&lt;pre&gt;4 specs, 1 failure in 0.014s
&gt; CSS tests (this is the name of the test suite that failed - as you could have multiple suites running this helps narrow it down)
&gt;&gt; should add class to element (this tells you the exact test that fails)
&gt;&gt;&gt; Expected 'myclassa myclassb newclass' to be 'x myclassa myclassb newclass'. (this tells you what the result actually was followed by what the test was expecting - so you can see where the result went wrong)
&gt;&gt;&gt;&gt; (after this you get a stack trace of what was executed so you can see specifics of where the error occurred)
&lt;/pre&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Hopefully this has given you a taster for how easy it is to get started writing unit-tests for your code (even if you don’t take the “write tests first” approach).&lt;/p&gt;
&lt;p&gt;There are many good unit-testing libraries available today and they each have their pros/cons as far as the API is concerned and the features they offer.&lt;/p&gt;
&lt;p&gt;I personally prefer Jasmine because I love the simplicity of the terminology and API and the flexibility I have to include my own &lt;em&gt;matchers&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;There are also libraries that focus on the more on specific parts of the testing process such as ‘mocks’, ‘stubs’ and ‘spies’ (see Sinon.js &lt;a href="http://sinonjs.org/"&gt;&lt;a href="http://sinonjs.org/"&gt;http://sinonjs.org/&lt;/a&gt;&lt;/a&gt;).&lt;/p&gt;</description><link>http://integralist.co.uk/post/15080179535</link><guid>http://integralist.co.uk/post/15080179535</guid><pubDate>Sat, 31 Dec 2011 13:29:00 +0000</pubDate></item><item><title>Host Methods vs Native Methods</title><description>&lt;p&gt;This was intended as a short (I failed) and overly simplified (I likely succeeded) post about Host methods and Native methods:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;What they are?&lt;/li&gt;
&lt;li&gt;How to detect them?&lt;/li&gt;
&lt;li&gt;When is it OK to modify them?&lt;/li&gt;
&lt;/ul&gt;&lt;!-- more --&gt;&lt;p&gt;&lt;strong&gt;What they are?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Native methods are built-in functions provided by the ECMAScript core specification. So things like Object methods (e.g. &lt;code&gt;Object.create&lt;/code&gt;), Array methods (e.g. &lt;code&gt;Array#forEach&lt;/code&gt;) etc.&lt;/p&gt;
&lt;p&gt;Host methods are functions provided by the host environment (most of the time when working in web development the host environment will be the user’s web browser). So things like the DOM API and the Events object are host objects/methods (e.g. &lt;code&gt;attachEvent&lt;/code&gt; is a host method and &lt;code&gt;addEventListener&lt;/code&gt; is a host method)&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How to detect them?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Detecting Native methods is relatively straight forward. The real problem comes when you need to determine whether the object/method you’re detecting actually works the way the specification dictates it should work. So just checking it is available to use isn’t good enough.&lt;/p&gt;
&lt;p&gt;Detecting host methods is similar but a lot more problematic, because the ECMAScript specification states that the host environment can implement certain methods however they like and so there is no guarantee that your checks for certain host methods (which may work today) will work in future.&lt;/p&gt;
&lt;p&gt;We’ll give an example of each so you can get an idea of what I mean…&lt;/p&gt;
&lt;p&gt;To detect a Native method such as &lt;span&gt;Array#forEach&lt;/span&gt; you should be able to do the following:&lt;/p&gt;
&lt;pre&gt;if (!Array.prototype.forEach) { /* polyfill for missing forEach method */ }&lt;/pre&gt;
&lt;p&gt;Note: polyfill is a term that Remy Sharp coined which means ‘a shim that mimics a future API’ (see: &lt;a href="http://remysharp.com/2010/10/08/what-is-a-polyfill/"&gt;&lt;a href="http://remysharp.com/2010/10/08/what-is-a-polyfill/"&gt;http://remysharp.com/2010/10/08/what-is-a-polyfill/&lt;/a&gt;&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;But the issue you could encounter in this example is if you’re inheriting a project from another developer and they have already extended the Native Array object with a forEach method and their polyfill version of the missing forEach function doesn’t work how the specification has dictated it should then you could find your code errors at hard to debug stages because of the difference in implementation where you’re passing parameters into a polyfill’ed method and that method hasn’t been implemented properly so the extra parameters either throw an error or (potentially worse) silently fail.&lt;/p&gt;
&lt;p&gt;This is where you either ‘suck it and see’ (which is a bad idea, but not always unavoidable), or you attempt genuine ‘feature detection’ which means (in this example) you create a test Array and test the forEach method works how you expect it to.&lt;/p&gt;
&lt;p&gt;The downsides to this approach (although it is the most robust and future-proof way of writing your code) is that all these checks are a performance penalty. If you’re sure the method you’re checking for is going to work how you expect it to then should you waste time/effort writing additional checks/tests to ensure the method works how the specification dictates? What happens if you do the full feature detection and discover the method doesn’t work how you expect it? You’ll still then need to implement some kind of fallback or lose the functionality that relies on that method.&lt;/p&gt;
&lt;p&gt;These are important decisions that need to be made and ones that are outside the realms of this post I’m afraid (simply because there are no easy answers).&lt;/p&gt;
&lt;p&gt;Now, detecting Host methods is actually worse because they can be implemented in any fashion the host environment chooses.&lt;/p&gt;
&lt;p&gt;So far it has been *noted* that checking the typeof result for a Host method will normally result in either &lt;span&gt;function&lt;/span&gt;, &lt;span&gt;object&lt;/span&gt;, &lt;span&gt;unknown&lt;/span&gt; or (recently I found…) &lt;span&gt;string&lt;/span&gt;, so if you get one of these back as a result then it’s a good chance the host object you’re checking for is available to use, but as you should be able to tell by now, this is a flawed process… fun heh!&lt;/p&gt;
&lt;p&gt;Again, this isn’t a reliable assumption to make, because in a future/new host environment they might have a typeof result that is none of the above. Literally you could check the typeof for a method and its result could be ‘&lt;em&gt;spacecraft&lt;/em&gt;’ - there are no rules as far as the Host environment is concerned!&lt;/p&gt;
&lt;p&gt;But for testing a host method exists, the following function has become the de-facto standard:&lt;/p&gt;
&lt;pre&gt;/*
	 * Feature Testing a Host Method
	 * Because a callable host object can legitimately have any typeof result then it can't be relied upon.
	 *
	 * @notes:
	 * The reason for the &amp;&amp; !!object[property] is because in ECMAScript version 3, 
	 * a null object has typeof result 'object' (which is considered a bug).
	 * In future versions (ECMAScript 5+) the typeof result will be 'null' (as it should be).
	 * 
	 * @reference: &lt;a href="http://michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting"&gt;http://michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting&lt;/a&gt;
	 */

	function isHostMethod(object, property) {
		var type = typeof object[property];

		return type == 'function' || // For Safari 3 typeof result being 'function' instead of 'object'
			   (type == 'object' &amp;&amp; !!object[property]) || // Protect against ES3 'null' typeof result being 'object'
			   type == 'unknown' || // For IE &lt; 9 when Microsoft used ActiveX objects for Native Functions
			   type == 'string'; // typeof for 'document.body[outerHTML]' results in 'string'
	}&lt;/pre&gt;
&lt;p class="p1"&gt;So lets take a quick re-cap of what’s going on here:&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;‘function’&lt;br/&gt; Most browsers typeof operator will result with ‘function’ when passed a callable host object&lt;br/&gt;&lt;br/&gt;&lt;/li&gt;
&lt;li class="li2"&gt;‘object’ &amp;&amp; !!object[property]&lt;br/&gt; In older versions of IE (less than 9) it implements some of its host objects not as Native functions but as ActiveX objects (admittedly this is deep browser implementation talk and normally you don’t need to know this stuff, but in this instance it’s important to understand what the heck is going on with IE + this will be very important when it comes to the following bullet-point and the ‘unknown’ result). &lt;br/&gt;&lt;br/&gt;Because some objects are actually ActiveX objects it means that those callable host objects have a typeof result of ‘unknown’ and those which are non-ActiveX objects have a typeof result of ‘object’ (so that’s why we’re checking for ‘object’). ON TOP OF THAT… remember that in the ECMAScript 3 specification it allows a Host environment typeof call to result in anything the host wants, so you’ll see in some browsers that the ‘null’ value has a typeof result of ‘object’ (which means a false positive for our conditional checks)! So that’s why in the second half of the check we’re converting the object[property] into a boolean (using the double exclamation mark operators !!) as this will convert a potential null value into false and so the check will fail, unless of course the value is ‘object’ which if so it will be converted to true and pass.&lt;br/&gt;&lt;br/&gt;&lt;/li&gt;
&lt;li class="li2"&gt;‘unknown’&lt;br/&gt; So, here comes that IE ActiveX object nonsense again. Any callable objects that are ActiveX objects will have a typeof result of ‘unknown’ - hence why we have this check here&lt;br/&gt;&lt;br/&gt;&lt;/li&gt;
&lt;li class="li2"&gt;‘string’&lt;br/&gt; Lastly, this is something I added myself as I discovered that checking for the outerHTML method that it actually was returning ‘string’ instead of ‘object’ or ‘function’ - which just goes to show how flawed host object detection is&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;When is it OK to modify them?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Modifying built-in Native objects isn’t as dangerous as host objects (as already noted by Kangax &lt;a href="http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/"&gt;&lt;a href="http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/"&gt;http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/&lt;/a&gt;&lt;/a&gt;) but care needs to be taken to ensure the augmented object works as the spec dictates (something that isn’t possible all the time, for example like with &lt;code&gt;Object.create&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;As far as host objects are concerned, never ever ever ever modify or augment them, just too dangerous.&lt;/p&gt;</description><link>http://integralist.co.uk/post/15029256999</link><guid>http://integralist.co.uk/post/15029256999</guid><pubDate>Fri, 30 Dec 2011 16:02:00 +0000</pubDate></item><item><title>jQuery Mobile: loading script files</title><description>&lt;p&gt;I’m working on a jQuery Mobile web application and I need to load specific JavaScript files for each page.&lt;/p&gt;
&lt;p&gt;This is a common thing to do and if you check the jQuery Mobile forum you’ll see lots of people are suffering from the same issue that occurs when trying to achieve this, which is that when loading a page using ajax, jQuery is stripping out the &lt;code&gt;&lt;script&gt;&lt;/code&gt; tags - I assume for security reasons to help protect the user, but then if they were doing that then they should be providing the user with a way to disable that feature as in my case I know the scripts I’m loading are safe.&lt;/p&gt;
&lt;p&gt;So far on the jQuery Mobile Forums I’ve only really seen the same ‘solution’ proposed over and over which is to have all your JavaScript in a single script file that you include on every page of your application. In my opinion: that stinks!&lt;/p&gt;
&lt;p&gt;I potentially will have LOTS of JavaScript code (in total) to load by the time my application is finished and the only solution proposed so far has been “hey, just load it all together on every page”.&lt;/p&gt;
&lt;p&gt;My solution: have a single script file that yes is included on every page of your application but acts as nothing more than a ‘bootstrapper’ file which detects the current page and then inserts the JavaScript file(s) into the DOM.&lt;/p&gt;
&lt;p&gt;Example is as follows…&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;First we need to write a function to insert our script(s):&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;function insertScript(script, container) {
	var elem = document.createElement('script');
	elem.type = 'text/javascript';
	elem.src = 'Assets/Scripts/' + script + '.js';
	container.appendChild(elem);
}
&lt;/pre&gt;
&lt;p&gt;Next we need to detect the current page (details are in the code comments):&lt;/p&gt;
&lt;pre&gt;// The 'pagechange' event is triggered after the changePage() request has finished loading the page into the DOM 
// and all page transition animations have completed.
// See: &lt;a href="https://gist.github.com/1336327"&gt;https://gist.github.com/1336327&lt;/a&gt; for some other page events
$(document).bind('pagechange', function(event){

// grab a list of all the divs's found in the page that have the attribute "role" with a value of "page"
	var pages = $('div[data-role="page"]'),
		// the current page is always the last div in the Array, so we store it in a variable
		currentPage = pages[pages.length-1],
		// grab the url of the page the  was loaded from (e.g. what page have we just ajax'ed into view)
		attr = currentPage.getAttribute('data-url');
	
	// basic conditional checks for the url we're expecting
	if (attr.indexOf('home.html') !== -1) {
		// now we know what page we're on we can insert the required scripts.
		// In this case i'm inserting a 'script.js' file.
		// I do this by passing through the name of the file and the 'currentPage' variable
		insertScript('search', currentPage);
	}
	
	// rinse and repeat...
	if (attr.indexOf('profile.html') !== -1) {
		insertScript('profile', currentPage);
	}
	
});
&lt;/pre&gt;
&lt;p&gt;That’s all there is to it.&lt;/p&gt;
&lt;p&gt;Let me know your thoughts or if you’ve found any better ways to work around this issue.&lt;/p&gt;</description><link>http://integralist.co.uk/post/12507317462</link><guid>http://integralist.co.uk/post/12507317462</guid><pubDate>Tue, 08 Nov 2011 09:16:00 +0000</pubDate></item><item><title>Beginners guide to AMD and RequireJs</title><description>&lt;p&gt;&lt;p class="p1"&gt;Here is a short list of what we’ll cover in this post:&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li1"&gt;&lt;a href="#hA"&gt;What is AMD?&lt;/a&gt;&lt;/li&gt;
&lt;li class="li1"&gt;&lt;a href="#hB"&gt;Why does it matter?&lt;/a&gt;&lt;/li&gt;
&lt;li class="li1"&gt;&lt;a href="#hC"&gt;How did we get here?&lt;/a&gt;&lt;/li&gt;
&lt;li class="li1"&gt;&lt;a href="#hD"&gt;How does RequireJs (and alternatives) fit in?&lt;/a&gt;&lt;/li&gt;
&lt;li class="li1"&gt;&lt;a href="#hE"&gt;Can we use jQuery?&lt;/a&gt;&lt;/li&gt;
&lt;li class="li1"&gt;&lt;a href="#hF"&gt;Basic Example&lt;/a&gt;&lt;/li&gt;
&lt;li class="li1"&gt;&lt;a href="#hG"&gt;What now?&lt;/a&gt;&lt;/li&gt;
&lt;li class="li1"&gt;&lt;a href="#hH"&gt;Links/Reference Material&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;h2 id="hA"&gt;&lt;!-- more --&gt;What is AMD?&lt;/h2&gt;
&lt;p class="p3"&gt;AMD stands for “Asynchronous Module Definition” and is a proposed API for loading modules (i.e. scripts) asynchronously.&lt;/p&gt;
&lt;h2 id="hB"&gt;Why does it matter?&lt;/h2&gt;
&lt;p class="p3"&gt;A few reasons, the summary of which is:&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li1"&gt;&lt;span class="s1"&gt;Performance&lt;/span&gt; (loading scripts asynchronously improves the loading speed of your web page).&lt;/li&gt;
&lt;li class="li1"&gt;&lt;span class="s1"&gt;Modular&lt;/span&gt; (which means code that is easier to maintain and re-use).&lt;/li&gt;
&lt;li class="li1"&gt;&lt;span class="s1"&gt;Best practice&lt;/span&gt; (helps to reduce global variables, maintain dependancies, and your code will follow guidelines that will in the future become the standards for the next iteration of JavaScript)&lt;/li&gt;
&lt;/ul&gt;&lt;h2 id="hC"&gt;How did we get here?&lt;/h2&gt;
&lt;p class="p3"&gt;The way we insert scripts into our pages has evolved over the years:&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li1"&gt;Multiple &lt;code&gt;&lt;script&gt;&lt;/code&gt; tags&lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;    &lt;script src="script-1.js"&gt;
    &lt;script src="script-2.js"&gt;
    &lt;script src="script-3.js"&gt;
&lt;/pre&gt;
&lt;ul class="ul1"&gt;&lt;li class="li1"&gt;Script Loader (e.g. LABjs / YepNope.js …and many many more)&lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;    // This example uses LABjs    
    &lt;script src="LAB.js"&gt;&lt;/script&gt;
    &lt;script&gt;
        $LAB.script('script-1.js').wait().script('script-2.js').script('script-3.js');
    &lt;/script&gt;
&lt;/pre&gt;
&lt;ul class="ul1"&gt;&lt;li class="li1"&gt;AMD Script Loader (e.g. RequireJs / Curl …and a couple of others)&lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;&lt;script data-main="main" src="require.js"&gt;&lt;/script&gt;&lt;/pre&gt;
&lt;p class="p3"&gt;The ‘multiple scripts’ has served us long and true, but means that the rendering of the page takes three times as long, as each &lt;code&gt;&lt;script&gt;&lt;/code&gt; tag must be downloaded, then executed before the browser can move onto the next &lt;code&gt;&lt;script&gt;&lt;/code&gt; (this is what is meant by loading scripts ‘synchronously’). Imagine if you are loading a JavaScript framework followed by a whole bucket full of plugins and then some of your own scripts. The page load time would increase quite significantly.&lt;/p&gt;
&lt;p class="p3"&gt;The way forward from there is using a ‘Script Loader’ which effectively lets you load multiple scripts asynchronously (i.e. in parallel with each other) so no waiting for one script, then moving to the next and waiting, and moving to the next. Unfortunately using a Script Loader doesn’t require your code to be modular in any real sense. So you can still have a mess of scripts all thrown together onto a page. Not to mention a few sketchy hacks are usually required to get these script loaders to load your scripts in the correct order so they don’t break the hell out of your web page.&lt;/p&gt;
&lt;p class="p3"&gt;So moving forward from that slightly better situation we come to ‘AMD Script Loaders’ which also lets you load scripts asynchronously but the scripts you are loading aren’t just a hodge podgy of random scripts pulled from the different corners of the web, they are well structured ‘modules’ that define their own dependancies and can be easily re-used across different projects because of their loose coupling with other scripts. They are also defined within their own scope so they don’t interfere with other scripts that may have been added by another developer before you, and so make it easier not to have a page full of global variables floating around causing havoc.&lt;/p&gt;
&lt;h2 id="hD"&gt;How does RequireJs (and alternatives) fit in?&lt;/h2&gt;
&lt;p class="p3"&gt;RequireJs is one of the more well known (and thus ‘popular’) AMD script loaders. It follows the ‘Modules Transport/C’ specification laid out by the CommonJs group (&lt;a title="CommonJs" target="_blank" href="http://wiki.commonjs.org/wiki/CommonJS"&gt;&lt;a href="http://wiki.commonjs.org/wiki/CommonJS"&gt;http://wiki.commonjs.org/wiki/CommonJS&lt;/a&gt;&lt;/a&gt;).&lt;/p&gt;
&lt;p class="p3"&gt;The RequireJs website has a lot of information to get you started, but can be a bit confusing for those new to the concept. So we’ll dive into some of our own examples which will make it easier to understand how you can use RequireJs and AMD in general in your projects.&lt;/p&gt;
&lt;h2 id="hE"&gt;Can we use jQuery?&lt;/h2&gt;
&lt;p class="p3"&gt;Sure! RequireJs actually has a special build of it that includes jQuery, but as jQuery too has seen AMD as the future, it has made itself AMD compatible (well, for those who might have more knowledge about AMD, it’s compatible in the sense that it can be loaded as a ‘named module’). &lt;/p&gt;
&lt;p class="p3"&gt;So for the 1.7 release of jQuery it will be possible to not need the RequireJs specific build that includes jQuery - you’ll be able to just load jQuery as a dependancy when defining your ‘module’.&lt;/p&gt;
&lt;h2 id="hF"&gt;Basic Example&lt;/h2&gt;
&lt;p class="p3"&gt;“OK, this is sounding groovy, how do I get involved?”&lt;/p&gt;
&lt;p class="p3"&gt;Well, to get you started I have a Github repo set-up which demonstrates the basics of using RequireJs (and trust me it’s basic, but then that’s the idea!)&lt;/p&gt;
&lt;p class="p3"&gt;&lt;a target="_blank" href="https://github.com/Integralist/RequireJs-Example/"&gt;&lt;a href="https://github.com/Integralist/RequireJs-Example/"&gt;https://github.com/Integralist/RequireJs-Example/&lt;/a&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p class="p3"&gt;There are comments in the code to help clarify what’s happening, but we’ll go over it here too.&lt;/p&gt;
&lt;p class="p3"&gt;The order of things will be:&lt;/p&gt;
&lt;ol class="ol1"&gt;&lt;li class="li1"&gt;Insert RequireJs into your web page.&lt;/li&gt;
&lt;li class="li1"&gt;Set-up the main script for the page (this script will load your other scripts (‘modules’) needed in this page).&lt;/li&gt;
&lt;li class="li1"&gt;Define your modules (ideally you’d define your modules first, but it made more sense to write it in this order).&lt;/li&gt;
&lt;li class="li1"&gt;Run a ‘build script’ when you’re ready to deploy your application (this takes your separate modules and combines them into a single script rather than having multiple scripts that need to be downloaded&lt;code&gt;**&lt;/code&gt;)&lt;/li&gt;
&lt;/ol&gt;&lt;p class="p3"&gt;&lt;code&gt;**&lt;/code&gt;There is a trade-off here. Some people will argue that multiple scripts loaded asynchronously is better than one monolithic script. If you’re code is written to be modular in the first place, then I believe running a build script that combines/minifies each module into a single script is better performing than multiple http requests for all these separate scripts (especially when you consider mobile devices where the connection can quite easily drop out while loading a page and caching resources is a lot more stringent)&lt;/p&gt;
&lt;p class="p3"&gt;So here we go…&lt;/p&gt;
&lt;p class="p3"&gt;&lt;span&gt;&lt;strong&gt;&lt;span class="s1"&gt;1. Insert RequireJs&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p class="p3"&gt;I keep all my files for my application/website in an ‘Assets’ folder.&lt;/p&gt;
&lt;p class="p3"&gt;For this example the structure would be:&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li1"&gt;Assets                               
&lt;ul class="ul2"&gt;&lt;li class="li1"&gt;Scripts                               
&lt;ul class="ul2"&gt;&lt;li class="li1"&gt;App                               
&lt;ul class="ul2"&gt;&lt;li class="li1"&gt;people.js&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li class="li1"&gt;Models                               
&lt;ul class="ul2"&gt;&lt;li class="li1"&gt;Person.js&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li class="li1"&gt;Utils                               
&lt;ul class="ul2"&gt;&lt;li class="li1"&gt;jquery.js&lt;/li&gt;
&lt;li class="li1"&gt;random.js&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li class="li1"&gt;Require.js&lt;/li&gt;
&lt;li class="li1"&gt;main.js&lt;/li&gt;
&lt;li class="li1"&gt;app.build.js (build script)&lt;/li&gt;
&lt;li class="li1"&gt;r.js (optimisation tool)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li class="li1"&gt;Styles                               
&lt;ul class="ul2"&gt;&lt;li class="li1"&gt;layout.css&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li class="li1"&gt;Images&lt;/li&gt;
&lt;li class="li1"&gt;Includes&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p3"&gt;In my main page I’ll insert the following script tag at the bottom of the page, just above the closing &lt;code&gt;&lt;/body&gt;&lt;/code&gt; tag…&lt;/p&gt;
&lt;pre&gt;&lt;script data-main="Assets/Scripts/main" src="Assets/Scripts/Require.js"&gt;&lt;/script&gt;&lt;/pre&gt;
&lt;p class="p3"&gt;…you’ll notice that we have specified a custom attribute on the script tag that points to our script folder and a file called ‘main’.&lt;/p&gt;
&lt;p class="p3"&gt;This does two things, it loads the Assets/Scripts/main.js file but it also tells RequireJs that all your other scripts are located in the Assets/Scripts folder as well.&lt;/p&gt;
&lt;p class="p3"&gt;&lt;span&gt;&lt;strong&gt;&lt;span class="s1"&gt;2. Set-up your ‘main’ script&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p class="p3"&gt;Inside main.js we have the following code…&lt;/p&gt;
&lt;pre&gt;    
    // This allows us to specify jQuery as a dependancy in one of our modules
    // You'll notice all paths are relative to Assets/Scripts/
    require.config({
        paths : {
            'jquery' : 'Utils/jquery'
        }
    });

    /*
        When we're defining a module we use the define() method.
        We'll see this used shortly.
        But as this is our main 'bootstrapping' script we're using the require() function instead.

        The require() function is similar to define() in that you pass it an optional array of dependencies, 
        and a function which will be executed when those dependencies are resolved. 
        However this code is not stored as a named module, as its purpose is to be run immediately.
    */

    require(["App/people"], function(iCanCallThisAnythingILike) {
        // The argument passed through is the returned value from the function definition we defined inside App/people.js
        // In this case it was an object literal with two properties: 'list' &amp; 'scripts'
        // If we had specified two dependancies then we'd pass through a second argument which again would be the return'ed value from that module
        
        console.log(iCanCallThisAnythingILike.list, iCanCallThisAnythingILike.scripts);
    });
&lt;/pre&gt;
&lt;p class="p3"&gt;So far we have our main script loading in a single dependancy (Assets/Scripts/App/people.js).&lt;/p&gt;
&lt;p class="p3"&gt;Lets have a look at that dependancy…&lt;/p&gt;
&lt;p class="p3"&gt;&lt;span&gt;&lt;strong&gt;&lt;span class="s1"&gt;3. Define your modules&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p class="p3"&gt;Here is the content of our ‘Assets/Scripts/App/people.js’ file…&lt;/p&gt;
&lt;pre&gt;    /*
     * You see we've specified the jQuery library as a dependency without specifying its correct path (we've just specified the name 'jquery').
     * This is because jQuery's AMD support is based on it being defined as a 'Named Module'.
     * So if you look at the script main.js (which is our bootstrapper file) you'll see we've set the require.config() to include the full path to jQuery.
     */

    define(["Models/Person", "Utils/random", "jquery"], function (Person, randomUtility, $) {

        // Notice that our dependancy modules(scripts) don't use the full path /Assets/Scripts/
        // This is because in our HTML page (where we loaded the RequireJs library) we had specified the main path already as a data- attribute on the script tag.
        // So RequireJs already knows that when we say 'Models/Person' we mean 'Assets/Scripts/Models/Person.js'

        var people = [],
            scriptsOnPage = $('script');

        people.push(new Person('Jim'));
        people.push(new Person(randomUtility.someValue));

        return { 
            list: people, 
            scripts: scriptsOnPage 
        };

});
&lt;/pre&gt;
&lt;p class="p3"&gt;Be aware that nothing should be declared outside of a single define() call. &lt;/p&gt;
&lt;p class="p3"&gt;All our modules work in the same way. We have a define() function that specifies some dependancies and then runs a callback when those dependancies have loaded, and then finally your module can return a value, object, function …etc.&lt;/p&gt;
&lt;p class="p3"&gt;In the above example you can see that this module has loaded jQuery as a dependancy (I mention this for those of you who love jQuery and want to make sure you can keep using it if you move to AMD - which is a definite “yes”).&lt;/p&gt;
&lt;p class="p3"&gt;Have a look at the modules defined in ‘Models/Person.js’ and ‘Utils/random.js’ to see that they work the same way.&lt;/p&gt;
&lt;p class="p3"&gt;&lt;span&gt;&lt;strong&gt;&lt;span class="s1"&gt;4. Run a build script&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p class="p3"&gt;RequireJs provides you with an optimisation script which you can run from the command line (I use the Terminal on the Mac, but your mileage may vary on Windows or other OS’) which helps you concatenate your different modules into one script and then minifies it for you and exports this single file into a folder of your choosing so you can link to this new file rather than your original main.js file (like we have at the moment). You could set-up the build script to just export it in the same folder as your main.js file and simply call it main.min.js if you like - up to you.&lt;/p&gt;
&lt;p class="p3"&gt;To run the build script we’re using NodeJs (as recommended by the author of RequireJs), but you can use Java as well if that’s your preference. Have a look at the RequireJs site to find out about that or if you need more information on installing NodeJs (as that is outside the realms of this post).&lt;/p&gt;
&lt;p class="p3"&gt;I’ve placed my build script (and the optimisation script) in the my main scripts folder ‘Assets/Scripts’ as I like to keep everything together (I know some people prefer to have this optimisation script completely separate from their project files, so you can place it wherever you feel comfortable).&lt;/p&gt;
&lt;p class="p3"&gt;My build script looks like this…&lt;/p&gt;
&lt;pre&gt;    /*
     * &lt;a href="http://requirejs.org/docs/optimization.html"&gt;http://requirejs.org/docs/optimization.html&lt;/a&gt;
     *
     * Use NodeJs to execute the r.js optimisation script on this build script
     * node r.js -o app.build.js
     *
     * See: &lt;a href="https://github.com/jrburke/r.js/blob/master/build/example.build.js"&gt;https://github.com/jrburke/r.js/blob/master/build/example.build.js&lt;/a&gt; for an example build script
     *
     * If you specify just the name (with no includes/excludes) then all modules are combined into the "main" file.
     * You can include/exclude specific modules though if needed
     *
     * You can also set optimize: "none" (or more specific uglifyjs settings) if you need to.
     */
    
    ({
        appDir: "../../",
        baseUrl: "Assets/Scripts",
        dir: "../../project-build",
        modules: [
            {
                name: "main"
                /*
                    include: ["App/people"],
                    exclude: ["Utils/random"]
                */
            }
        ]
    })
&lt;/pre&gt;
&lt;p class="p5"&gt;See the code comments above for the command you need to use to execute the build script using the optimisation tool.&lt;/p&gt;
&lt;p class="p3"&gt;As you can see above we could tell the build script to ‘include’ or ‘exclude’ specific modules. I’ve not needed to use this yet, but as I understand it this ‘excluding’ of modules is useful for debugging purposes (can anyone confirm this)?&lt;/p&gt;
&lt;p class="p3"&gt;The above build script only takes a second and it generates a lovely single script file called main.js and actually places it *outside* of my website directory into a folder called ‘project-build’ (i don’t like to risk accidentally over-writing my source JavaScript files… if you know what I mean).&lt;/p&gt;
&lt;h2 id="hG"&gt;What now?&lt;/h2&gt;
&lt;p class="p3"&gt;Well… start using AMD in your projects. &lt;/p&gt;
&lt;p class="p3"&gt;The best way to learn it is to use it. Try out some of the basic structural changes to get yourself used to architecting your apps in a modular fashion, and then just go for it!&lt;/p&gt;
&lt;p class="p3"&gt;I’ve covered RequireJs here, but I’ve heard good things about &lt;a title="@unscriptable" target="_blank" href="http://twitter.com/#!/unscriptable"&gt;@unscriptable&lt;/a&gt;’s Curl loader (&lt;a href="https://github.com/unscriptable/curl"&gt;&lt;a href="https://github.com/unscriptable/curl"&gt;https://github.com/unscriptable/curl&lt;/a&gt;&lt;/a&gt;) so I’d recommend checking that out too.&lt;/p&gt;
&lt;h2 id="hH"&gt;Links/Reference Material&lt;/h2&gt;
&lt;ul class="ul1"&gt;&lt;li class="li1"&gt;&lt;a target="_blank" href="https://github.com/amdjs/amdjs-api/wiki/AMD"&gt;&lt;a href="https://github.com/amdjs/amdjs-api/wiki/AMD"&gt;https://github.com/amdjs/amdjs-api/wiki/AMD&lt;/a&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li class="li1"&gt;&lt;a target="_blank" href="http://unscriptable.com/index.php/2011/03/30/curl-js-yet-another-amd-loader/"&gt;&lt;a href="http://unscriptable.com/index.php/2011/03/30/curl-js-yet-another-amd-loader/"&gt;http://unscriptable.com/index.php/2011/03/30/curl-js-yet-another-amd-loader/&lt;/a&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li class="li1"&gt;&lt;a target="_blank" href="http://wiki.commonjs.org/wiki/CommonJS"&gt;&lt;a href="http://wiki.commonjs.org/wiki/CommonJS"&gt;http://wiki.commonjs.org/wiki/CommonJS&lt;/a&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/p&gt;</description><link>http://integralist.co.uk/post/11705798780</link><guid>http://integralist.co.uk/post/11705798780</guid><pubDate>Thu, 20 Oct 2011 22:29:00 +0100</pubDate><category>AMD</category><category>RequireJs</category><category>JavaScript</category></item><item><title>JavaScript The Definite Guide (Taken with instagram)</title><description>&lt;img src="http://27.media.tumblr.com/tumblr_llweeahzXQ1qhzbzmo1_500.jpg"/&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;JavaScript The Definite Guide (Taken with &lt;a href="http://instagr.am"&gt;instagram&lt;/a&gt;)&lt;/p&gt;</description><link>http://integralist.co.uk/post/5925036726</link><guid>http://integralist.co.uk/post/5925036726</guid><pubDate>Sat, 28 May 2011 10:01:22 +0100</pubDate></item><item><title>How to use Git and GitHub</title><description>&lt;p&gt;If you’re having trouble understanding how to get up and running with GitHub, or you just wanted to find a free version-control system and heard about this thing called ‘Git’ then hopefully the following information should help…&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;When I first heard about GitHub I was unsure as to its purpose and why it was such a hit with other developers. I had never heard of ‘Git’ before and whenever people spoke of GitHub they would mention Git at the same time, and so because they both had ‘Git’ in their name I just assumed they were one and the same thing - which as it turns out was quite wrong indeed.&lt;/p&gt;
&lt;p&gt;To clarify, ‘Git’ is a program. Once installed on your computer it can be accessed via the Command Line. You could very well have yourself a nice little ‘version control’ set-up on your computer using just Git and without ever needing to look at, or even having heard of, ‘GitHub’.&lt;/p&gt;
&lt;p&gt;GitHub on the other hand is a website that hosts Git ‘files’ (known as ‘repositories’) and so it makes it a lot easier for open-source projects to have other developers help extend the project by allowing these developers to grab(&lt;code&gt;fork&lt;/code&gt;) the project code (even though they didn’t create the project on GitHub) and to duplicate the project set-up and to modify it however the developer wishes and then allow the developer to submit changes, bug fixes, new features etc back to the original developers to integrate if they were so inclined.&lt;/p&gt;
&lt;p&gt;It’s an incredibly powerful tool.&lt;/p&gt;
&lt;p&gt;So with this in mind it’s best to learn about Git first, so then using GitHub will suddenly make a whole lot more sense!  And this is why I think I struggled with GitHub initially: because I had no idea about what Git was and how it worked.&lt;/p&gt;
&lt;p&gt;To help you read through this post, I’ve broken the page down into sections:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="#0"&gt;Using the GitHub interface&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#1"&gt;Installing Git&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2"&gt;Setting up a new Git repository&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3"&gt;Adding files for Git to track&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4"&gt;Commiting files to Git&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5"&gt;Setting up a GitHub account&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#6"&gt;Generating an SSH Public Key&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#7"&gt;Creating a new GitHub repository&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#8"&gt;Pushing your project up to GitHub’s repository&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#9"&gt;Removing/Editing files&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#10"&gt;Git Tips&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#11"&gt;Tell Git to ignore certain files and formats&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#12"&gt;Best practices for Commit Messages&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;But before we get started…&lt;/p&gt;
&lt;h2 id="0"&gt;Using the GitHub interface&lt;/h2&gt;
&lt;p&gt;Now I know I said we would start with learning Git first, THEN GitHub. But it is worth noting at this stage (mainly by &lt;a href="http://twitter.com/paul_irish"&gt;@paul_irish&lt;/a&gt;’s request) that you can in fact update files directly via the GitHub website!&lt;/p&gt;
&lt;p&gt;So if you want to avoid the command line altogether but you still want to help work with open-source projects on GitHub and in the simplest/easiest way possible, then read this section only and stop there (as the rest of the sections of this post will likely be of no interest to you).&lt;/p&gt;
&lt;p&gt;If on the other hand using the GitHub interface doesn’t interest you at all and you really want to learn about what Git is and how to use it (and thus be able to use GitHub more effectively) then just skip this section and move onto “&lt;a href="#1"&gt;Installing Git&lt;/a&gt;”.  So first thing you guys want to do is to sign-up for a GitHub account here:&lt;/p&gt;
&lt;p&gt;&lt;a href="https://github.com/signup/free"&gt;&lt;a href="https://github.com/signup/free"&gt;https://github.com/signup/free&lt;/a&gt;&lt;/a&gt; (to get to this page you need to go through the ‘Pricing and Signup’ link at the top of the GitHub home page, and from there you’ll be able to find the ‘free’ account set-up).&lt;/p&gt;
&lt;p&gt;Once you’ve got your free account created you can start using GitHub for the more ‘basic’ Git features, such as ‘forking’ (i.e. taking a copy of…) an open-source project and making changes to it.  We’ll create a new &lt;code&gt;fork&lt;/code&gt; of the ‘jQuery JavaScript Library’ and start making some changes to the code base, and then submitting ‘commits’ to our own copy of the jQuery library project (i.e. saving our project’s current state).   Then when happy with our changes we’ll submit a &lt;code&gt;pull&lt;/code&gt; request to the jQuery owners! (and basically, by ‘pull’ we’re really saying “please jQuery, accept our humble changes we’ve made to your code base - we’d love for you to integrate them into the jQuery source”).  So let’s take a look at the jQuery JavaScript Library page here:&lt;/p&gt;
&lt;p&gt;&lt;a href="https://github.com/jquery/jquery"&gt;&lt;a href="https://github.com/jquery/jquery"&gt;https://github.com/jquery/jquery&lt;/a&gt;&lt;/a&gt;.  On this page you should see a ‘fork’ link near the top right of the page. Click on it. You’ll notice that GitHub will start making a copy of the jQuery JavaScript Library project and will generate a new project within your account under the same name (e.g. I had the following URL generated:&lt;/p&gt;
&lt;p&gt;&lt;a href="https://github.com/Integralist/jquery"&gt;&lt;a href="https://github.com/Integralist/jquery"&gt;https://github.com/Integralist/jquery&lt;/a&gt;&lt;/a&gt;).  Now, you’ll see a list of all the files within this project and you can click on any folder/file to see its content. So let’s take a look at the README.md file by clicking on it’s name. You’ll see that GitHub does a nice little AJAX sliding animation and then shows you the README.md file… wonderful.&lt;/p&gt;
&lt;p&gt;The next step is to click the ‘Edit this file’ link, which you’ll see on the right-hand side of the page. The file you were looking at has now moved into ‘edit’ mode and so you can start typing out some changes to the file (obviously if you’re a developer then you can open up the core JavaScript files and start making tweaks there in the same way).&lt;/p&gt;
&lt;p&gt;After you’ve made the changes you wanted to the file, simply move to the input field below the file, just where it says “Commit message” and enter a description of the change you made (note: if the changes you are making are for your own personal use then just write whatever you like, but if you are actually planning on submitting your changes to jQuery to integrate into the source then you’ll need to find out what jQuery requires you to include within the ‘commit’ message - for example the jQuery UI project has written up some submission guidelines here: &lt;a href="http://wiki.jqueryui.com/w/page/25941597/Commit-Message-Style-Guide"&gt;&lt;a href="http://wiki.jqueryui.com/w/page/25941597/Commit-Message-Style-Guide"&gt;http://wiki.jqueryui.com/w/page/25941597/Commit-Message-Style-Guide&lt;/a&gt;&lt;/a&gt; and so I assume there are similar guidelines for the main jQuery project).&lt;/p&gt;
&lt;p&gt;Once your commit message has been entered then you can click the “Commit Changes” button at the bottom of the page.  Now when the page reloads you’ll see the latest note/commit for this file is actually yours and shows your commit message. But this is still only changes to *your* copy of the jQuery library.&lt;/p&gt;
&lt;p&gt;You need to now tell jQuery about your very important change and get them to integrate it into their source version. To do this you now need to click the “Pull Request” link at the top of the page (near where you clicked on the “Fork” link from earlier.   Clicking the “Pull Request” link will redirect you to a page where you must enter a message to go along with your commit (this will be reviewed by core committers!).  Final step! Click “Send pull request” at the bottom of that page (just under where you entered your message).&lt;/p&gt;
&lt;p&gt;From here you can sit back and relax, I think? Again I’ve read somewhere previously (for jQuery UI) that you need to add a link to your commit to the ticket in their tracker system (jQuery may very well have something similar I’m not sure though).  But enough of this GUI nonsense, lets start using Git how it was meant to be used… on the command line!&lt;/p&gt;
&lt;h2 id="1"&gt;Installing Git&lt;/h2&gt;
&lt;p&gt;OK, first thing first, lets get Git installed (by the way I work on a Mac so hopefully this guide is still somewhat useful to PC users).  I personally found the easiest way to install git is via a pre-compiled installer: &lt;a href="http://code.google.com/p/git-osx-installer/"&gt;&lt;a href="http://code.google.com/p/git-osx-installer/"&gt;http://code.google.com/p/git-osx-installer/&lt;/a&gt;&lt;/a&gt; (UPDATE: see my reply to &lt;a href="http://twitter.com/Mathias"&gt;@Mathias&lt;/a&gt;’ &lt;a href="http://integralist.co.uk/how-to-use-git-and-github/#comment-456"&gt;comment&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;There are installers for PC as well as Mac and Linux so take your pick and you can install from the original Git source code but that’s a bit more ‘involved’.  The official GitHub website mentions many ways to install Git, but I found the pre-compiled installer the quickest/easiest way - I pretty much ran the installer and it was done in about two seconds flat.&lt;/p&gt;
&lt;p&gt;When Git is installed the first thing we’ll probably want to do is to tell it what our name and email is (this way, when working with a system - such as GitHub - and having multiple users working on your code base you can easily see which users made changes to the code - and tell them off if they added/removed code that broke your application).&lt;/p&gt;
&lt;p&gt;To inform Git what your username and email address is, open the Terminal application on your Mac and enter:&lt;/p&gt;
&lt;pre&gt;git config --global user.name "Joe Bloggs"
git config --global user.email "joe@bloggs.com"
&lt;/pre&gt;
&lt;p&gt;You can check these settings at any time within the Terminal by typing:&lt;/p&gt;
&lt;pre&gt;git config user.name
git config user.email
&lt;/pre&gt;
&lt;p&gt;Next you want to make sure that Git ignores any ‘white space’ changes. Now this needs a little bit extra explanation: Git tracks file ‘&lt;em&gt;content&lt;/em&gt;’ and NOT individual files. So if you add an empty new line to a file (and Git is tracking that file) then Git will inform you that the file has been modified but you don’t really want a single empty line to be flagged up to you (not in web development really as white space is not that important). To have Git ignore whitespace changes you can enter the following into the Terminal:&lt;/p&gt;
&lt;pre&gt;git config --global apply.whitespace nowarn
&lt;/pre&gt;
&lt;p&gt;Now that we’ve got Git set-up we need to look at how we can tell it to ‘track’ certain files &amp; folders in your project.&lt;/p&gt;
&lt;h2 id="2"&gt;Setting up a new Git repository&lt;/h2&gt;
&lt;p&gt;Now, using Git does require a tiny bit of command line knowledge (such as navigating your computer via command line, making new directories and files, removing files etc). I’ll try and cover as much of this as I think is needed to use Git (you may need more commands than I cover but then I’ll leave that up to you to look into further).  OK, so with the Terminal still open, navigate to your project folder (we do this by using the &lt;code&gt;cd&lt;/code&gt; command - which stands for ‘change directory’)…&lt;/p&gt;
&lt;pre&gt;cd ~/Dropbox/Project/
&lt;/pre&gt;
&lt;p&gt;…as you can see I have a folder called ‘Project’ within a private &lt;a href="http://www.dropbox.com/"&gt;Dropbox&lt;/a&gt; folder. The tilda character &lt;code&gt;~&lt;/code&gt; simply tells Terminal to go back to your home directory and start looking from there for the folder you need.  You can also navigate your Mac using &lt;code&gt;../&lt;/code&gt; to go up and down folders.  If you want to check the contents of a particular folder then simply type &lt;code&gt;ls&lt;/code&gt; which tells Terminal to ‘list’ the content of the current folder.&lt;/p&gt;
&lt;p&gt;Once you’re inside the project folder you’ll need to create an empty Git ‘repository’, which means Git will create a hidden folder called &lt;code&gt;.git&lt;/code&gt; where it will store all files and references it needs to be an effective version-control system for this project folder.  To create a new Git repository type the following (make sure you’re definitely in your main project folder):&lt;/p&gt;
&lt;pre&gt;git init
&lt;/pre&gt;
&lt;p&gt;If you’re Mac is set-up to not show ‘hidden’ folders then it wont look like much has happened (although you will now see a message in the Terminal telling you a new empty repository was created).  If you really want to see hidden files and folders on your Mac then type the following into the Terminal…&lt;/p&gt;
&lt;pre&gt;defaults write com.apple.Finder AppleShowAllFiles YES
killall Finder
&lt;/pre&gt;
&lt;p&gt;…the first line tells Finder to allow showing of hidden files, and the second line restarts Finder so you can see the changes take effect.  Once you have a new Git repository set-up you need to tell Git what files/folders to start ‘tracking’.&lt;/p&gt;
&lt;h2 id="3"&gt;Adding files for Git to track&lt;/h2&gt;
&lt;p&gt;If you don’t already have any files in your project folder then we can at least add one file (via the Terminal as well) which will become useful later when you start to use GitHub as a code sharing platform.   To create a file via the Terminal we must use the &lt;code&gt;touch&lt;/code&gt; command like so…&lt;/p&gt;
&lt;pre&gt;touch README.md
&lt;/pre&gt;
&lt;p&gt;…the above line creates a ‘README.md’ file (which is used by GitHub to give a project you create a visible description).  Now as it happens I already had a few files in my project folder so along with the README.md file I just created I’m going to start adding these files to Git’s “Staging Area”.&lt;/p&gt;
&lt;p&gt;The Staging Area is a place to add your files/folders before ‘commiting’ the changes you’ve made to these files and then (if you need to…) pushing the changed files onto a remote server (such as we’ll be doing later when we push our files up to our GitHub repository).  To add a file/folder to the Staging Area (and thus have Git start ‘tracking’ the files and their changes) enter…&lt;/p&gt;
&lt;pre&gt;git add README.md
&lt;/pre&gt;
&lt;p&gt;…this tells Git to start tracking the README.md file, but we could have specified multiple files at once using a space to separate the file names such as…&lt;/p&gt;
&lt;pre&gt;git add file1 file2 file3
&lt;/pre&gt;
&lt;p&gt;…we could also tell Git to track ALL files/folders currently found within this folder…&lt;/p&gt;
&lt;pre&gt;git add *
&lt;/pre&gt;
&lt;p&gt;…and lastly if you’re coming back to an existing project you can tell Git to track any new ‘un-tracked’ files using the line…&lt;/p&gt;
&lt;pre&gt;git add .
&lt;/pre&gt;
&lt;p&gt;…the period character (.) simply means ‘any un-tracked files’ and saves you having to remember which new files are or aren’t being tracked already.  The &lt;code&gt;add&lt;/code&gt; command makes it easy to add as many files as you like to Git’s “Staging Area”.&lt;/p&gt;
&lt;p&gt;You can add some files, go away and make a cup of tea, work on something else and then come back and add some more files to the Staging Area.  But for any of these files to be ‘committed’ and thus have a ‘snap shot’ of the project (so we can - if we need to - revert back to an older version) we need to use the &lt;code&gt;commit&lt;/code&gt; command to tell Git we want it to snap shot our project in its current state…&lt;/p&gt;
&lt;h2 id="4"&gt;Commiting files to Git&lt;/h2&gt;
&lt;pre&gt;git commit -m 'Add a README file to help explain the project'
&lt;/pre&gt;
&lt;p&gt;…the above command uses the &lt;code&gt;-m&lt;/code&gt; ‘flag’ which means you’re about to add a comment to go along with this ‘commit’. You don’t have to use the &lt;code&gt;-m&lt;/code&gt; flag, but if you don’t then Terminal will try and open the default text editor so you can enter your commit description and I find it quicker and easier just to use the &lt;code&gt;-m&lt;/code&gt; command.&lt;/p&gt;
&lt;p&gt;Now that we’ve been acquainted with Git, and created a new Git repository, added some files and committed them to Git we can start looking at using a remote server for collaborating on our project. To do this we’re going to use &lt;a href="https://github.com/"&gt;&lt;a href="https://github.com/"&gt;https://github.com/&lt;/a&gt;&lt;/a&gt; the ‘Social Coding’ website.&lt;/p&gt;
&lt;h2 id="5"&gt;Setting up a GitHub account&lt;/h2&gt;
&lt;p&gt;Note: if you need extra help (beyond what I’ve shared) then you can refer to the official GitHub help pages here: &lt;a href="http://learn.github.com/p/setup.html"&gt;&lt;a href="http://learn.github.com/p/setup.html"&gt;http://learn.github.com/p/setup.html&lt;/a&gt;&lt;/a&gt; So the first thing to do is to register for an account (you have to go through the ‘Pricing and Signup’ page to find the ‘free’ account set-up): &lt;a href="https://github.com/signup/free"&gt;&lt;a href="https://github.com/signup/free"&gt;https://github.com/signup/free&lt;/a&gt;&lt;/a&gt; (as you’ll see on that page, there are paid for options available so your team of developers can collaborate with a version-controlled project using GitHub’s servers, rather than having to work out how to set-up their own ‘remote’ server to push code changes to).&lt;/p&gt;
&lt;p&gt;Once you’ve signed up, I recommend the first thing you do is to create a SSH Public Key (you’re going to need it to be able to securely access remote files - and by ‘remote’ I mean access your project files on the GitHub server).  GitHub have a useful page for explaining how to set-up the SSH Public Key: &lt;a href="http://help.github.com/mac-key-setup/"&gt;&lt;a href="http://help.github.com/mac-key-setup/"&gt;http://help.github.com/mac-key-setup/&lt;/a&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Most of you will find that you can skip the first part of the page and head straight down to the section titled ‘Generating a key’ (I mention how to set-up your SSH Public Key below, but do have a read over the provided link as it should help clarify what to do).&lt;/p&gt;
&lt;h2 id="6"&gt;Generating an SSH Public Key&lt;/h2&gt;
&lt;p&gt;Basically, in the Terminal you type…&lt;/p&gt;
&lt;pre&gt;ssh-keygen -t rsa -C "joe@bloggs.com"
&lt;/pre&gt;
&lt;p&gt;…obviously change the email address from &lt;code&gt;joe@bloggs.com&lt;/code&gt; to whatever email address you used to sign-up to GitHub with.  Terminal will then tell you…&lt;/p&gt;
&lt;pre&gt;Generating public/private rsa key pair.
Enter file in which to save the key (/Users/tekkub/.ssh/id_rsa):
&lt;/pre&gt;
&lt;p&gt;…but your message will be slightly different in that the directory path in the brackets (e.g. &lt;code&gt;(/Users/tekkub/.ssh/id_rsa)&lt;/code&gt;) will likely be different on your computer.&lt;/p&gt;
&lt;p&gt;The next thing to do is to simply press &lt;code&gt;ENTER&lt;/code&gt; and Terminal will generate a new SSH Public Key within the hidden ‘id_rsa’ file it mentions (if you didn’t hit &lt;code&gt;ENTER&lt;/code&gt; then the Terminal would expect you to enter the name of a file to save the SSH Public Key into - so I didn’t bother messing around doing that and just saved the key into the file the Terminal suggested I use).  Next Terminal will ask you to enter a pass phrase…&lt;/p&gt;
&lt;pre&gt;Enter passphrase (empty for no passphrase):
&lt;/pre&gt;
&lt;p&gt;…I advise you enter a good password which you wont forget and just press &lt;code&gt;ENTER&lt;/code&gt; again (Terminal will ask you to enter the same pass phrase again, so it’s sure you know what you typed).&lt;/p&gt;
&lt;p&gt;Now Terminal will have generated your SSH Public Key, and you’ll need to provide this public key to GitHub so it knows it’s you connecting to its server and trying to change your project files.  If you’ve never seen an SSH Public Key before then you may be mistaken that the gobble-dee-gook that the Terminal spit out at you after your last command was the SSH Public Key. Wrong!&lt;/p&gt;
&lt;p&gt;You can’t see the key, but you can copy it to your clipboard (for pasting into the GitHub website).  So now open your web browser and head back to your GitHub account page and look for the link in your account page for entering an SSH Public Key (direct link: &lt;a href="https://github.com/account#ssh_bucket"&gt;&lt;a href="https://github.com/account#ssh_bucket"&gt;https://github.com/account#ssh_bucket&lt;/a&gt;&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;Now go back to the Terminal and enter the following command to copy your SSH Public Key to your clipboard…&lt;/p&gt;
&lt;pre&gt;cat ~/.ssh/id_rsa.pub | pbcopy
&lt;/pre&gt;
&lt;p&gt;…once copied into your clipboard, go back to the relevant GitHub SSH page and paste your key in and save the changes to your account settings.  This now leaves just one last thing for you to do while logged into the GitHub website and that is to create a new ‘repository’.&lt;/p&gt;
&lt;h2 id="7"&gt;Creating a new GitHub repository&lt;/h2&gt;
&lt;p&gt;To create a new repository you’ll need to go to this page &lt;a href="https://github.com/repositories/new"&gt;&lt;a href="https://github.com/repositories/new"&gt;https://github.com/repositories/new&lt;/a&gt;&lt;/a&gt; (you’ll find links all over the place for creating a new repository, but it’s easier if I just link to it for you).&lt;/p&gt;
&lt;p&gt;Now enter the information GitHub asks for (I created a repository called ‘Project Template’ and it generated the following URL: &lt;a href="https://github.com/Integralist/Project-Template"&gt;&lt;a href="https://github.com/Integralist/Project-Template"&gt;https://github.com/Integralist/Project-Template&lt;/a&gt;&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;Once you’ve created a new repository on GitHub, it will show you some Terminal commands you can run for setting up Git locally and pushing the project file to GitHub’s online repository.&lt;/p&gt;
&lt;h2 id="8"&gt;Pushing your project up to GitHub’s repository&lt;/h2&gt;
&lt;p&gt;In the Terminal, lets make sure we’re still in our project directory…&lt;/p&gt;
&lt;pre&gt;cd ~/Dropbox/Project/
&lt;/pre&gt;
&lt;p&gt;…once we’re back in our project folder we can now set-up our remote server access…&lt;/p&gt;
&lt;pre&gt;git remote add origin git@github.com:Integralist/Project-Template.git
&lt;/pre&gt;
&lt;p&gt;…OK, so what’s happening here? Well, we’re telling Git that we want to add a remote server and store it under the easy to remember name of ‘origin’. We could of called ‘origin’ anything we liked…  E.g. ‘MyRemoteServer’&lt;/p&gt;
&lt;pre&gt;git remote add MyRemoteServer git@github.com:Integralist/Project-Template.git
&lt;/pre&gt;
&lt;p&gt;…the line that follows the name we gave is the URL for the GitHub repository we created (and you’ll see this URL on your project page when you first set-up a new repository).  Now that we have created an &lt;code&gt;origin&lt;/code&gt; to hold our remote server information we can now ‘push’ our project online to GitHub…&lt;/p&gt;
&lt;pre&gt;git push origin master
&lt;/pre&gt;
&lt;p&gt;…the above line uses the &lt;code&gt;push&lt;/code&gt; command to tell your local Git to push your latest ‘commit’ to the specified remote server.&lt;/p&gt;
&lt;p&gt;Now the word &lt;code&gt;master&lt;/code&gt; which you can see at the end of the command simply refers to the default ‘branch’ that is set-up (I don’t go into the details of it here, but Git allows you to &lt;code&gt;branch&lt;/code&gt; off your code.&lt;/p&gt;
&lt;p&gt;So for example, if we decided we wanted to add some new features to our project, which could end up breaking things if not properly tested, we could create another branch called ‘new_feature’ which would be a complete copy of the current project for us to work from - and that way we leave the original ‘master’ branch untouched so we can continue to work on maintaining that copy of the project and allowing us to fix any bugs found in it while developing the new feature, then when the new feature is ready and tested we can then &lt;code&gt;merge&lt;/code&gt; the new feature back into our ‘master’ branch - but these are all commands left for another time).&lt;/p&gt;
&lt;p&gt;Now, back to the &lt;code&gt;push&lt;/code&gt; command: As it is our first push, the Terminal will not be able to authenticate the host ‘github.com’ so we’ll just type ‘yes’ to confirm we trust it.  For me, the push failed the first time I tried - this I found out straight away afterwards was because I needed to enter my pass phrase.&lt;/p&gt;
&lt;p&gt;After it failed the first time I typed the &lt;code&gt;git push origin master&lt;/code&gt; command again and this time the Terminal displayed a dialog window asking me to enter my passphrase for accessing my SSH Public Key.  I entered my passphrase and then the push started to proceed successfully.&lt;/p&gt;
&lt;p&gt;Now we can start pushing files any time we like to this particular project.  I had a file called ‘robots.txt’ in my project.&lt;/p&gt;
&lt;p&gt;Lets say I made an update to the file ‘robots.txt’ - I can push that on it’s own:&lt;/p&gt;
&lt;pre&gt;git add robots.txt
git commit -m 'Add some new robot configurations'
git push origin master
&lt;/pre&gt;
&lt;h2 id="9"&gt;Removing/Editing files&lt;/h2&gt;
&lt;p&gt;To remove a file (e.g. lets remove the ‘robots.txt’ file) simply type…&lt;/p&gt;
&lt;pre&gt;git rm robots.txt
&lt;/pre&gt;
&lt;p&gt;…then do the normal commit with message and push.&lt;/p&gt;
&lt;pre&gt;git commit -m 'Remove the robots.txt file'
git push origin master
&lt;/pre&gt;
&lt;p&gt;To edit existing files is the same process as adding files. But beware, as you’ll get an error if the file hasn’t actually been changed!&lt;/p&gt;
&lt;p&gt;Remember, Git tracks file &lt;em&gt;content&lt;/em&gt;, NOT individual files. So it wont like you wasting its time by uploading files that haven’t changed at all.&lt;/p&gt;
&lt;h2 id="10"&gt;Git Tips&lt;/h2&gt;
&lt;p&gt;Any time you need to check the status of a &lt;code&gt;.git&lt;/code&gt; repository:&lt;/p&gt;
&lt;pre&gt;git status
&lt;/pre&gt;
&lt;p&gt;Show all Git commands:&lt;/p&gt;
&lt;pre&gt;git
&lt;/pre&gt;
&lt;p&gt;Show where Git was installed:&lt;/p&gt;
&lt;pre&gt;which git
&lt;/pre&gt;
&lt;p&gt;Show all recent activity:&lt;/p&gt;
&lt;pre&gt;git log
&lt;/pre&gt;
&lt;p&gt;Show all activity (all branches):&lt;/p&gt;
&lt;pre&gt;git log --all
&lt;/pre&gt;
&lt;p&gt;Show all activity (all branches) in a tree view (slightly more readable):&lt;/p&gt;
&lt;pre&gt;git log --graph --all
&lt;/pre&gt;
&lt;p&gt;Show all activity (all branches) in a tree view (slightly more readable) BUT only shows the bare minimum details (i.e. the first seven characters of the hash and the commit message):&lt;/p&gt;
&lt;pre&gt;git log --graph --all --online
&lt;/pre&gt;
&lt;p&gt;Shows all branches for this repository: NOTE: the Terminal will display all branches available with an asterisk (*) before the branch name that is currently activated…&lt;/p&gt;
&lt;pre&gt;git branch
&lt;/pre&gt;
&lt;p&gt;Create a new branch called “my_new_branch” which is a complete copy of ‘master’ for you to mess around with:&lt;/p&gt;
&lt;pre&gt;git branch my_new_branch
&lt;/pre&gt;
&lt;p&gt;Switch to a different branch:&lt;/p&gt;
&lt;pre&gt;git checkout my_new_branch
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;IMPORTANT! When you switch between branches, the .git file (that contains all information about your repository) will show you a different set of files in Finder! So if you switch to the new branch you just created &lt;code&gt;my_new_branch&lt;/code&gt; and then added a new file to your project’s directory (e.g. mynewfile.php), then this new file will be visible in Finder while you are still viewing the &lt;code&gt;my_new_branch&lt;/code&gt; branch. The moment you switch back to the &lt;code&gt;master&lt;/code&gt; branch the ‘mynewfile.php’ file will disappear from view. &lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Whatever changes were made on one branch will not be visible at all from the other branches. Since Git tracks contents, this works for files and whole directories down to lines and characters.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The following command means you don’t need to use ‘git add’ you can just commit all tracked files&lt;/p&gt;
&lt;pre&gt;git -a commit
&lt;/pre&gt;
&lt;p&gt;Git has a GUI tool for visualisation of commits/changes:&lt;/p&gt;
&lt;pre&gt;gitk
&lt;/pre&gt;
&lt;p&gt;By default it shows only the branch you are currently viewing - if you want it to show both branches at once the use &lt;code&gt;gitk --all&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If I wanted to merge a new branch ‘name_of_branch’ with my master branch then I would call:&lt;/p&gt;
&lt;pre&gt;git merge name_of_branch
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;NOTE: It’s important to switch view back to the main branch you wish to merge other code with.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Show all commits to this file (and who made them):&lt;/p&gt;
&lt;pre&gt;git blame file_name
&lt;/pre&gt;
&lt;p&gt;To ‘tag’ a particular commit in your projects history - this could be a version number for a script update…&lt;/p&gt;
&lt;pre&gt;git tag tag_name (e.g. git tag v0.5.6)
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;NOTE: tags must have no spaces (e.g. my_first_tag):&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;An annotated tag:&lt;/p&gt;
&lt;pre&gt;git tag -a tag_name
&lt;/pre&gt;
&lt;p&gt;An annotated tag with a comment:&lt;/p&gt;
&lt;pre&gt;git tag -a tag_name -m "my first release candidate"
&lt;/pre&gt;
&lt;p&gt;To push your tags you need to do the following - because &lt;code&gt;git push&lt;/code&gt; alone wont do it (thanks to &lt;a href="http://twitter.com/mathias"&gt;@mathias&lt;/a&gt; for this information):&lt;/p&gt;
&lt;pre&gt;git push --tags
&lt;/pre&gt;
&lt;p&gt;Show all tags in this project:&lt;/p&gt;
&lt;pre&gt;git tag
&lt;/pre&gt;
&lt;p&gt;Show the last commit:&lt;/p&gt;
&lt;pre&gt;git show
&lt;/pre&gt;
&lt;p&gt;Show the last commit that had this tag assigned after it (acts like a bookmark):&lt;/p&gt;
&lt;pre&gt;git show tag_name
&lt;/pre&gt;
&lt;p&gt;The following command only works after looking at a tag:&lt;/p&gt;
&lt;pre&gt;git describe
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Note: it shows the name of the tag followed by how many commits have happened since its inception (as well as the first seven characters from the hash that references the commit, and the -g is not part of the hash; it’s a suffix that stands for “Git” - according to the Git documentation it “useful in an environment where people may use different SCMs”).&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt; &lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;e.g. my_first_tag-1-gd8a7d27&lt;/em&gt;&lt;/p&gt;
&lt;h2 id="11"&gt;Tell Git to ignore certain files and formats&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;.gitignore&lt;/code&gt; is a file that you can create to hold rules about what items Git should ignore.&lt;/p&gt;
&lt;p&gt;A good example of using .gitignore is if you wanted a config script - e.g. Settings.php -  that held your database username/password ignored so it wasn’t accidentally pushed to a public repository (such as GitHub):&lt;/p&gt;
&lt;p&gt;You can use a &lt;code&gt;#&lt;/code&gt; as a comment line and then specify the types of files or specific files to be ignored, such as:&lt;/p&gt;
&lt;pre&gt;#Mac OS X files
.DS_Store

# VIM leave-behinds
*.swp
&lt;/pre&gt;
&lt;p&gt;You can also ignore all files of a certain type except one by using the bang (&lt;code&gt;!&lt;/code&gt;) such as:&lt;/p&gt;
&lt;pre&gt;*.log
!errors.log
&lt;/pre&gt;
&lt;h2 id="12"&gt;Best practices for Commit Messages&lt;/h2&gt;
&lt;p&gt;As requested by &lt;a href="http://twitter.com/Mathias"&gt;@Mathias&lt;/a&gt; (on quite a few occasions…) there are a few best practices to consider when writing your commit messages.&lt;/p&gt;
&lt;p&gt;One of the most obvious and useful is to split your commit message into a ‘summary’ and ‘body’ (this is done by including a blank line in-between the first and second lines of your commit message).&lt;/p&gt;
&lt;p&gt;The ‘summary’ should (ideally) be no more than 50 characters. This is so that when other users are viewing your commit messages (via different means) then they can always understand what the commit is about, and then if they wish to read the full commit message (i.e. the ‘body’ part - which should include further information on the specifics of the commit) then they can do.&lt;/p&gt;
&lt;p&gt;And there are quite a few places where the ‘summary’ part of your commit message would come in really helpful to other users…&lt;br/&gt;&lt;br/&gt;The following bullet points are credited to &lt;a href="http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html"&gt;tbaggery.com&lt;/a&gt;:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;code&gt;git log --pretty=oneline&lt;/code&gt; - shows a terse history mapping containing the commit id and the summary&lt;/li&gt;
&lt;li&gt;&lt;code&gt;git rebase --interactive&lt;/code&gt; - provides the summary for each commit in the editor it invokes&lt;/li&gt;
&lt;li&gt;if the config option &lt;code&gt;merge.summary&lt;/code&gt; is set, the summaries from all merged commits will make their way into the merge commit message&lt;/li&gt;
&lt;li&gt;&lt;code&gt;git shortlog&lt;/code&gt; uses summary lines in the changelog-like output it produces&lt;/li&gt;
&lt;li&gt;&lt;code&gt;git format-patch&lt;/code&gt; git send-email, and related tools use it as the subject for emails&lt;/li&gt;
&lt;li&gt;reflogs, a local history accessible with git reflog intended to help you recover from stupid mistakes, get a copy of the summary&lt;/li&gt;
&lt;li&gt;&lt;code&gt;gitk&lt;/code&gt; has a column for the summary&lt;/li&gt;
&lt;li&gt;GitHub uses the summary in various places in their user interface&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;When writing your commit message it’s probably a good idea to write in the ‘present tense’ (e.g. ‘fix’ rather than ‘fixed’) - this is to help keep consistency between other git commands such as &lt;code&gt;git merge&lt;/code&gt; | &lt;code&gt;git revert&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Also, when writing the ‘body’ part of your commit message, make sure to keep the character length to 72 per line. Feel free to read up on the details of why at &lt;a href="http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html"&gt;tbaggery.com&lt;/a&gt;, but the principle is basically that using certain git commands on certain set-ups could cause the text to overflow off the edge of the screen. The previous link also includes some tips on how to achieve this via Vim or TextMate.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;And that’s about it for the “Git Basics”. There is so much more that you can learn and I can’t recommend the book “Getting Good with Git” enough! Go check that out here: &lt;a href="http://rockablepress.com/books/getting-good-with-git/"&gt;&lt;a href="http://rockablepress.com/books/getting-good-with-git/"&gt;http://rockablepress.com/books/getting-good-with-git/&lt;/a&gt;&lt;/a&gt;.&lt;/p&gt;</description><link>http://integralist.co.uk/post/3551693739</link><guid>http://integralist.co.uk/post/3551693739</guid><pubDate>Sun, 27 Feb 2011 22:12:00 +0000</pubDate><category>git</category><category>github</category><category>version control</category></item><item><title>Regex Popup Window</title><description>&lt;p&gt;This is a quick post to show you how to open up external website links within a pop-up window (without adding extra non semantic mark-up to your HTML code).&lt;/p&gt;
&lt;p&gt;In the past I’ve heard a lot of people talk about adding either custom attributes or using existing attributes such as &lt;code&gt;rel&lt;/code&gt; as a hook for your JavaScript code to find links that should open in a pop-up window. I disagree, and suggest using Regular Expressions (regexes) along with some procedural code to help figure this out for you (it will save you the time and hassle of adding this extra mark-up yourself).&lt;/p&gt;
&lt;p&gt;&lt;!-- more --&gt;This solution is an updated version. The previous version was recklessly using &lt;a target="_blank" href="http://www.regular-expressions.info/brackets.html"&gt;capture groups&lt;/a&gt; when really they should have been using non-capturing groups (as the brackets in the following solution are solely for applying &lt;a target="_blank" href="http://www.regular-expressions.info/repeat.html"&gt;quantifiers&lt;/a&gt; and &lt;a target="_blank" href="http://www.regular-expressions.info/optional.html"&gt;optional items&lt;/a&gt;). The reason you should use capturing groups sparingly is to do with performance and saving the regex engine from having to remember content within the capturing groups.  The &lt;strong&gt;Regular Expression&lt;/strong&gt; checks for things like whether the URL is an SSL protected URL and uses a &lt;a target="_blank" href="http://www.regular-expressions.info/lookaround.html"&gt;negative look ahead assertion&lt;/a&gt; to make sure that it doesn’t incorrectly match URL’s that *appear* to be external (e.g. they start with a http) but in fact actually are links to the current website URL (this happens a lot with Content Management Systems where a user will copy and paste the full URL to one of their own pages).&lt;/p&gt;
&lt;h2&gt;The (&lt;em&gt;original&lt;/em&gt;) Regex Solution&lt;/h2&gt;
&lt;pre class="regex"&gt;^http(?:s)?:\/\/(?!(?:www.)?integralist)&lt;/pre&gt;
&lt;h2&gt;Example Code&lt;/h2&gt;
&lt;pre&gt;/**
 * The Integralist global namespace object.
 *
 * @class Integralist
 * @singleton
 * @static
 */
function Integralist() {
   // Constructor
}

/**
 * Augment the Integralist class so it includes a method
 * which finds all &lt;a&gt; elements that link to an external website
 * and sets them to open in a popup window
 */
Integralist.prototype.external = function() {
   var that = this; // Required to keep scope within the following Closure
   this.settings = 'location=yes,resizable=yes,width=' + screen.availWidth + ',height=' + screen.availHeight + ',scrollbars=1,left=0,top=0';
   this.popup = function(node) {
      var url = node.href;
      return function() {
         window.open(url, 'external' , that.settings);
         return false;
      };
   };

   var a = document.getElementsByTagName('a'), // Private variable to store HTMLCollection of all &lt;a&gt; elements
       len = a.length, // Store array length in variable
       pattern = /^http(?:s)?:\/\/(?!(?:www.)?integralist)/; // RegExp pattern to match any external URL's but not the current website

   // Loop through the array checking for any A elements that link to an external URL
   while (len--) {
      var element = a[len].getAttribute('href');
      if (pattern.test(element)) {
         a[len].onclick = this.popup(a[len]);
      }
   }
};

// Create a singleton of the Integralist Class
var Integralist = new Integralist();

// Trigger 'external' method
window.onload = Integralist.external;
&lt;/pre&gt;
&lt;h2 id="update1"&gt;Update 1&lt;/h2&gt;
&lt;p&gt;Tweaked the regex again to make it simpler. Decided using a character class for just a single dot character was pointless, might as well just escape the dot. Also got rid of the non-capturing group around the s in https and just used an optional token &lt;code&gt;?&lt;/code&gt; on its own as again it was pointless wrapping a single character in a non-capturing group.&lt;/p&gt;
&lt;pre class="regex"&gt;^https?:\/\/(?!(?:www\.)?integralist)&lt;/pre&gt;
&lt;h2 id="update2"&gt;Update 2&lt;/h2&gt;
&lt;p&gt;I’ve ended up tweaking the regex again to take into account files that don’t start with http but should still open in a pop-up window. For example if a website links to a self hosted PDF file it might store it in the following directory path &lt;code&gt;Assets/Documents/MyFile.pdf&lt;/code&gt;.  First thing I did was add a case-insensitive modifier flag (which I simply forgot last time).  Now to work around the issue of linking to internal documents that should open in a pop-up I place a non-capturing group after the opening anchor &lt;code&gt;^&lt;/code&gt;. Within this group it has a character class that allows a period &lt;code&gt;.&lt;/code&gt; and a forward slash &lt;code&gt;/&lt;/code&gt; and uses a quantifier &lt;code&gt;+&lt;/code&gt; so it matches 1 or more times. I then make the whole group optional.  Next, we take the original regex and wrap it in a non-capturing group and place it after the preceding code. Inside the non-capturing group, at the start we add the name of the directory we are looking for (in this case I just need to look for the word “Assets” and I know it’s going to link to a document and not a HTML file). I then put in the alternator meta-character so it will look for “Assets” and if it can’t find it the regex engine will backtrack to this point and try the rest of the regex which we’ve already discussed.  So the final regex looks like this…&lt;/p&gt;
&lt;pre class="regex"&gt;^(?:[.\/]+)?(?:Assets|https?:\/\/(?!(?:www\.)?integralist))&lt;/pre&gt;</description><link>http://integralist.co.uk/post/3551378490</link><guid>http://integralist.co.uk/post/3551378490</guid><pubDate>Sun, 27 Feb 2011 21:54:00 +0000</pubDate><category>regex</category><category>regular expressions</category></item><item><title>JavaScript Inheritance</title><description>&lt;p&gt;&lt;a target="_blank" href="http://en.wikipedia.org/wiki/Class_(object-oriented_programming)"&gt;Class based inheritance&lt;/a&gt; doesn’t exist in JavaScript. You can replicate its syntax but you’re better off learning how JavaScript implements its own form of inheritance (it’s much more efficient and easier to maintain code shared amongst other JavaScript developers).&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;The basic premise is this: JavaScript functions created using the &lt;code&gt;new&lt;/code&gt; keyword work in a similar way to what Class based languages know as ‘Constructors’. When a function uses the &lt;code&gt;new&lt;/code&gt; keyword the Function object is given a &lt;code&gt;prototype&lt;/code&gt; property which points (initially) to an empty object. This empty object can then have methods and properties added to it which will be available to all other objects that point their own prototype link to it.  A basic example is as follows…&lt;/p&gt;
&lt;pre&gt;var Person = function(settings) {
   if (!settings) { settings = {}; } // code defensively

   // Instance properties (any new instances of the Person class will have these properties)
   this.name = settings.name || 'no name given';
   this.age = settings.age || 'no age given';

   // Instance method (any new instances of the Person class will have this method)
   this.getName = function() {
      alert(this.name);
   };
};

// Create a new instance of the Person Class
var integralist = new Person({ name:'Mark McDonnell', age:28 });

// Add a method to this instance of the Person Class only (no other instances created will have this method)
integralist.getAge = function() {
   alert(this.age);
}

// Test the integralist instance has access to both methods
integralist.getName();
integralist.getAge();

// Create another instance of the Person Class
var user = new Person();

// Notice the user has access to a 'getName' method but not a 'getAge' method
user.getName();

// I know this will error so I'm wrapping it in a try statement
try {
   user.getAge();
} catch(err) {
   alert(err); // Uncaught TypeError: Object [object Object] has no method 'getAge'
}

// Add a method to the Person Class' prototype chain (all instances of the Person Class will now get this method - even those already defined)
Person.prototype.getNameAndAge = function() {
   alert('Hi, my name is ' + this.name + ', and I\'m ' + this.age + ' years old.');
}

// Test this new method is accessible to all instances of the Person Class
integralist.getNameAndAge();
user.getNameAndAge();&lt;/pre&gt;
&lt;p&gt;&lt;br/&gt;This is prototypal inheritance in action.  The Mozilla Developer Network has written up a short article on the differences between Class-based and Prototype-based languages which you can find here: &lt;a target="_blank" href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model#Class-Based_vs._Prototype-Based_Languages"&gt;&lt;a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model#Class-Based_vs._Prototype-Based_Languages"&gt;https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model#Class-Based_vs._Prototype-Based_Languages&lt;/a&gt;&lt;/a&gt;&lt;/p&gt;</description><link>http://integralist.co.uk/post/3550348841</link><guid>http://integralist.co.uk/post/3550348841</guid><pubDate>Sun, 27 Feb 2011 20:56:00 +0000</pubDate><category>JavaScript</category><category>oop</category><category>object-oriented programming</category><category>inheritance</category></item></channel></rss>

