Tuesday 26 February 2013

git hooks rock on Windows 8!

I love git, I absolutely love it!

I particularly love it because it allowed me to deploy to the now defunct PHPFog... I developed an application for a friend on PHPFog but when they said they were closing down and suggested that existing users move to AppFog I was less than pleased! That was until I spent a rainy Saturday afternoon getting my head around the af command and I started to like it.

That was until Windows 8 died on me and I had to do a fresh install. I managed to get git up and running again eventually, probably thanks to the encouragement of Ravishankar Somasundaram and his cracking Git: Version Control for Everyone. Then I started looking around to see if I could still use git in a meaningful way and found this lovely link about git hooks.

Now I develop on Windows 8 and it's not as simple as all that to get your head around but the way I did it was to go to the git hooks github site and copy the resulting script into Sublime Text 2 (Go on, buy it!). Save it as git-hooks (sans file extention) into C:\Program Files (x86)\Git\cmd, or wherever git resides. Then, within your project directory run git hooks --install. This creates an empty hooks folder within your .git directory. Now the fun begins...

Basically you'll need to create a .bat file to run. I needed it to run after git commit so I deleted all the files except for post-commit and replaced all the text in there:

af login --email <email address> --passwd <password>
af update <project_name>
echo Updated

Now I can keep my version control in place and I don't need to worry about deploying the project as git does it for me ;-).

Sunday 24 February 2013

Making a web page 02: It's a tree in winter!

The last time we looked at how a web page is a tree (at least in my head) but that tree isn't made up of wood. In a web page the tree is made up of words.

The words are in a form that a browser knows how to deal with in terms of what should be appear on the page, that form is HTML.

I've written an awful lot about HTML in the past as part of my dissertion but at it's simplest it's a word wrapped in angle brackets ("<" and ">"). When the browser sees angle brackets it knows it's got to take special notice, perks up it's ears and does what we (as the authors of the HTML) say.

The browser is a forgiving thing though so it does it's best to try and do what we say when we give it odd instructions... but we really shouldn't confuse it if we can help it!

HTML was created by Tim Berners-Lee - you might remember him from the opening ceremony of the 2012 London Olympics - he's pretty cool and one of my heroes!

From what I understand he was working at CERN and wanted a way of transmitting his scientific findings to other scientists in the early days of the internet. He looked at a technology called SGML which was used as a language for sharing big projects and was meant to be read by computers. He took the bits he needed from SGML and created HTML and the rest is history.

In order for a browser to understand what we want it to do we have to tell it that we're going to be giving it some HTML, we do this by adding a document type declaration (a DOCTYPE) on the first line of any web page we give it. This used to be a somewhat complicated thing as there were any number of types of HTML. We're presently working with HTML5 which has cleared up a lot of confusion and makes writing HTML a lot less hard. HTML5s DOCTYPE is easy: <!DOCTYPE html>. See, it was so important it needed an exclamation point at the beginning!

Seeing as we've just told the browser that we're going to be giving it HTML it seems a little odd to then start the next line of a file with <html> but we really should as otherwise we'ed have no trunk (that tree gets everywhere). Going back to the picture we looked at before of the really rather cool tattoo can you guess what goes next?

That's right, we're going to be putting <head> next. Before we close the head and start on the body we really should tell the browser what language we're going to be using <meta charset="utf-8" />. This allows the browser to know what character set (charset) to use. There's another interesting thing about that charset declaration though, did you notice the "/"? That tells the browser that that tag (or element if you'd prefer) doesn't contain anything else. It doesn't look in vain for the ending of that particular branch as we've told it that that's it. This leads to my next question: how do we close the head?

If you've never seen HTML it's probably an unfair question so I'll tell you: we close the head with </head>.

Another thing that a head should have is a title, we put the title within the head like this: <title>My Title</title>. Easy ehh?

Now you've got a pretty good idea after what goes after the head haven't you? That's right we'll put everything we want to be displayed within the body. That's our two main branches taken care of. But we really need to remember to close the trunk. I'm almost certain you know how to do that now. That's right, we'll close the trunk with </html>.

If you've followed on with this we know that at it's most basic a web page looks like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>My Title</title>
    </head>
    <body>
    </body>
</html>

Wow, that's a lot of work just to get to an empty page. But if a web page is a tree then this is a tree in winter when all the leaves have fallen (and a fair few branches apart from the main two). Write this in a text editor of your choice and save it as index.html and you'll be able to see it in all it's stark beauty - and it really is beautiful! You've just written something that a machine can understand! Clever old you!

Just to check run it through something that understands HTML. Go to the W3Cs Markup Validation Service, click the "Validate by Direct Input" tab at the top and paste in your HTML. Hopefully you'll get a nice "This document was successfully checked as HTML5!" message. If not then look at the HTML above again and check that it's all alright!

Saturday 23 February 2013

Easy menus on vanilla hosting (GDrive or site44)

Way back when (I'm not too sure about how long ago now) I volunteered to work on a site for a charity. This was when I was first starting out in the web and I wanted to not only produce a good finished product but I also wanted to test out all sorts of new techniques. I seem to remember making JavaScript jump through all sorts of loops in order to make the menu for the site. Someone ran it through an analyser though and because the analyser wasn't very good and because I'd misused JavaScript to such an extent it failed in terms of SEO. Chastened I re-wrote it using server side (PHP) includes and felt a little disappointed.

Things have changed though!

I love the idea of free and a mate's nephew recently asked about getting his first website up and running easily and cheaply. I pointed him to site44, simply sign up for a free Dropbox account, link the two and you can edit files on your local machine and see the result on the internet using a site44 URI. Brilliant!

Then a couple of weeks back I got to hearing about Google allowing shared folders to serve their content, including HTML. I just had to have a play with this and so came about my rather limited site hosted on GDrive (an easier URI to remember is http://gdriv.es/drmsite).

But getting back to my original point: I use BootStrap a lot now in order to standardise the look and feel of my stuff. As such I have a lovely fixed menu bar on all pages but remembering to add each and every new page I create is a pain in the arse! I also follow the pattern of creating each new project in it's own directory. This meant that I got to starting to think about using JavaScript to create the menu on each page. I'd need to define the new project in one place and one place only and JavaScript would do the rest!

So I created a vars.js file:

var links = [
    {
        "url":"folder1",
        "text":"Project 1"
    },
    {
        "url":"folder2",
        "text":"Project 2"
    },
    {
        "url":"folder3",
        "text":"Project 3"
    },
    {
        "url":"folder4",
        "text":"Project 4"
    },
    {
        "url":"folder5",
        "text":"Project 5"
    },
    {
        "url":"folder6",
        "text":"Project 6"
    }
];
var base = "<The public link to your shared folder>";

The <The public link to your shared folder> link is an interesting one and is explained in greater detail on this comment on lifehacker.

I also created a simple functions.js:

$(function(){
    if(getDir() === base){
        $.each(links, function(k,v){
            $("#siteLinks").append($("<li></li>").append($("<a></a>", {
                "href": v.url,
                "text": v.text
            })));
        });
    }else{
        var dir = getDir();
        $.each(links, function(k,v){
            if(dir === base + "/" + v.url){
                $("#siteLinks").append($("<li></li>", {
                    "class": "active"
                }).append($("<a></a>",{
                    "href": "./",
                    "text": v.text
                })));
            }else{
                $("#siteLinks").append($("<li></li>").append($("<a></a>", {
                    "href": "../" + v.url,
                    "text": v.text
                })));
            }
        });
    }
});

function getDir(){
    var path = document.location.pathname;
    var dir = path.substring(path.indexOf('/', 1)+1, path.lastIndexOf('/'));
    return dir;
}
This means that all I need to do include vars.js and functions.js in each file and make sure that my menu declaration has this snippet of HTML:
<div class="nav-collapse">
    <ul class="nav" id="siteLinks"></ul>
</div>

Easy ehh?

UPDATE

I've updated the script, listing is here: http://drmsite.blogspot.co.uk/2013/03/multi-level-bootstrap-menu-on-gdrive-or.html.

Thursday 21 February 2013

Making a web page 01: It's a tree!

#2 son asked about teaching him how to make a webpage again today...

I've a tendency to get rather excited so thought that rather than put him off with my enthusiasm I'd take it nice and slow. This, then, is a very gentle introduction to making a web page - I hope it'll form part of a series of posts.

You're looking at this text which is contained within a webpage which might be part of a website and your looking at it through a browser. The browser isn't the internet, the browser is merely a way of accessing a subset of the information which is available on the internet and which is formatted in a certain way. It's formatted using a markup language that the browser can understand called HTML. That's not to say that HTML (HyperText Markup Language) isn't utterly brilliant (it is) but it's not all that the internet is for. It is what an awful lot of it is used for these days but it isn't the only thing out there.

As you now know you're viewing HTML though a browser let me blow your mind by saying that the page you're on now is seen, by me at least, as a tree! Each paragraph you've seen is a leaf on that tree, the picture of a tree above is also a part of the tree. I like trees!

Whilst it might be hard to see the page you're looking at as a tree think about the books on your shelves, they - at the most basic - are also trees. That there stuff you put in your car in order to make it go (no, not parents) is - at the most basic level - dead dinosaurs!

I might be taking the analogy a little far but you get the idea?

Anyway. The trunk of the tree that is this web page is called (have you guessed it yet?) the html tag (we call the parts of the trees tags a lot of the time, but they can also be called elements). It's getting on for being the most important part of a web page but also the part that is most often ignored (Even browsers ignore it sometimes). There are only two branches coming from the trunk but everything else hangs from those two branches.

Here I'm going to mix metaphors a little and tell you that these first two tags/elements are called the head and the body. A human is made up of much the same two things, as I guess the following picture illustrates:

See you again soon.

Tuesday 19 February 2013

Dirty data

We're having to process a lot of dirty data at work. We're spinning through data from a legacy system and parsing the data which has been kept in all sorts of different formats for address data.

An awful lot of data doesn't have spaces where you'd think spaces should be so I'm left looking for solutions... I thought about abbreviating the strings using Intelligent String Abbreviation from the lovely JSPRO.COM:

function abbreviate(str, max, suffix){
  if((str = str.replace(/^\s+|\s+$/g, '').replace(/[\r\n]*\s*[\r\n]+/g, ' ').replace(/[ \t]+/g, ' ')).length <= max){
    return str;
  }
  var abbr = '',
  str = str.split(' '),
  suffix = (typeof suffix !== 'undefined' ? suffix : ' ...'),
  max = (max - suffix.length);
  for(var len = str.length, i = 0; i &lt; len; i ++){
    if((abbr + str[i]).length &lt; max){
      abbr += str[i] + ' ';
    }else { 
      break; 
    }
  }
  return abbr.replace(/[ ]$/g, '') + suffix;
}

But after thinking about it I clocked that it was simply a question of replacing "," with ", " but only when the comma wasn't being followed by a space. I guess that HTML would be fine with more than one space but it offended my sensibilities to indiscriminately replace commas with commas and spaces...

This, however, does the trick very nicely (Thanks Lars):

var str = str.replace(/[\,^\s]/g,", ");
UPDATE 1

I've been using this for a while now and I clocked a problem. I now use this instead:

var str = str.replace(/\,/g, ', ').replace(/'  '/g, ' ');

I think that the second replace is extraneous as browsers interpret multiple white spaces as a single space but it's better to be safe than sorry ;-).

UPDATE 2

While the above works it's not as elegant as I would like so after a bit more research I've now got this:

str.replace(/,\s*/g,", ");

Much cleaner!