OiNutter.co.uk

What semi-colon?

Introducing Skeletor and Grayskull

So this month I’ve been playing with something new… again (I’m going through an experimental phase I guess). This month it was Ruby, or more specifically Ruby Gems. I’ve used Ruby a little in the Rakefiles I use for building my javascript projects but not really done any major work with it, until now.

I’ve been trying to find a nice simple solution for setting up my project skeletons quickly and easily. I’d thought of some sort of Git repository but then I’d end up with some faffy process involving multiple branches for different project types and having to clone a repository and then remove the git repository in the newly cloned folder and well, this didn’t sound quick or easy. Eventually I hit on the idea of a command line ruby gem that could use templates defining a directory structure to set up what I needed. A quick search turned up nothing that seemed to do the job, the closest thing was Mr Bones but that seemed to be entirely for Ruby projects and the template skeleton wasn’t easily customisable.  I was disappointed that it existed though as I wanted to name my gem bones but hey, how many things am I going to write that I can actually justify calling Skeletor?

So I started looking into what was involved in creating ruby gems. Initially I started of using Jeweler but this created a lot of stuff I didn’t really understand so I decided to strip everything back and just look at the structure of some gems I already used. My main source of reference was Sprockets but I also used Capistrano when trying to understand the command line aspect of the gem. These gave me a good source of reference for what was required in the various gem files.

For anyone who’s not created gemfiles before the basic folder structure is as follows:

  • lib - contains 1 ruby file with the same name as the gem and a folder also named after the gem which contains all the code for the gem
  • bin - optional folder that contains the command line executable files for the gem
  • test - contains the unit test files
  • a Gemfile that contains the dependencies for the gem
  • a.gemspec file that contains the configuration details for building the gem
  • the usual README and LICENSE files in your choice of format

I’m not going to go into the details of each of those files.  I’d say the best thing to do is to check out the source of some of the gems that you use and that will probably give you the best understanding of what’s required. I’m using Thor for the command line interface and Hike to locate the files in the 2 possible load paths.

Skeletor supports defining a directory structure with files and folders. You can also specify include files which will be copied into the directory, either from a local file or a remote url, and define build tasks to be run after the directory is set up.

The code for Skeletor is actually pretty simple. Ruby’s built in YAML.load function converts the template file into a Ruby Hash object which can then be looped through and there is a JSON gem that works in the same way. The most complicated part was the validation code as I needed to be able to specify custom data types that a node could match any one of.  The only gem I could find for YAML validation was Kwalify but that wasn’t flexible enough for what I needed so I had to write my own. I eventually managed to get a working validation class that worked for what I wanted and decided to extract it into it’s own gem so it could be used for other projects, and thus Grayskull was born.

Grayskull will validate JSON and YAML files against a given schema including matching against custom types. All the details for how to create the schema are at the GitHub page, as are the instructions on how to install and use it. The same goes for Skeletor. Grayskull is also using Thor for the command line as well as the aforementioned JSON gem for validation.

Check out the GitHub repositories for the source code and instructions.

Skeletor | Grayskull

A Fistful of Documentation

Thanks to an issue raised on Uncharted by a fellow GitHub user pointing out that a lack of good examples was stopping people see if my work was any good and worth using I’ve started going through all my projects and making sure they all have proper example pages and decent instructions in their README files.

So far the following have been updated:

Obscura - Examples | Documentation
Uncharted - Examples | Documentation
Ermintrude - Examples | Documentation
tipBox - Examples | Documentation

Objective-C and iOS Development - Taking My First Steps

I recently managed to get myself a Macbook, which besides finally giving me a home computer that can cope with what I’m throwing at it, has finally enabled me to start looking at iOS development. I’ve briefly played with Android development but what little Java skills I picked up at university and was able to remember after all this time weren’t quite up to the task. So you’d think that tackling developing in Objective-C, a language I’ve never used, would be an even bigger challenge right? Well thankfully I managed to find some help, primarily from iTunes U. If anyone hasn’t checked this out yet I’d highly recommend it, there are a load of free to download lectures from several of the big universities on there (primarily US from what I could see but there were some others). The course I’ve been following is Stanford’s cs193p course on iOS application development by Paul Hegarty. If you can get past Paul’s slightly eccentric seeming nature, anyone wanting to get into iOS development would do well to check this out. I’m only a few lectures in at the moment but the course has already succeeded in helping me finally get my head around MVC.

So what do I think of Objective-C? Well I’m still in my early stages of playing with the language so this is really just a first impression but I think I’m going to like developing in it, and I certainly think I’m going to find it easier and more enjoyable than I ever did Java. It’s very different from most of the languages I’ve ever learned and certainly a huge change from the languages I use on a daily basis (PHP and Javascript). One of the first things I’ve noticed is how verbose it is. There is very much a convention of the code reading like plain english, with things such as long variable names and methods. The way methods are defined is one of the primary examples I would give of this verbosity, and of the difference of Objective-C to languages I’m used to. The following examples show a comparison of how methods are defined in Actionscript 3 (I know, I know, but it’s the only langauge I know well enough to write comparison code in that defines the return and argument types) and Objective-C.

As you can see the single argument methods are pretty straight forward, return type at the start, followed by the method name, then the argument and it’s type listed after a semi colon (felt weird having no brackets). From what I’ve seen there doesn’t seem to be any indication of public or private with the method definitions. What seems to happen is that you just don’t define methods you want to be private in your header file, which defines the class’ public api. The - at the start of the definition indicates that this is an instance method, a + indicates a static method. The primary difference in the way methods are defined is when it comes to methods with multiple arguments, where you see this splitting of the method name. The only real purpose I can see of this is that if you write your method names and variables properly it helps the code read like plain english.

As for developing in XCode, so far I’m liking it. The built-in Interface Builder Gui tools are really helpful, especially when it comes to linking the controller to your views.  It’s taking me a little while to find everything in the property inspectors, possibly because what I’m looking for isn’t available for customisation but you never know. The in-line error and warning highlighting is really helpful as it makes it much easier to see where you’ve missed that semi-colon or curly brace. I think I’m really going to like the property synthesization (more on that once I’ve gone more in-depth with it) that allows the compiler to auto generate methods for you.

Developing for iOS is going to present me with some new challenges that I wouldn’t normally have to contend with such as Memory Management, which is going to take some getting used to, but that’s half the fun. So hopefully before too long I’ll be posting about my new app that you can all go and buy and make me millions, (although based on how many readers I probably have  I might be lucky to make a pound!).  I promise it won’t be a new fart app!

Obscura - Canvas, CoffeeScript and Micro Frameworks

It’s been a busy few months so I’m a bit behind on my posting so hopefully I can get back on schedule now. Once again I’ve been working on another javascript library, this time a canvas based image manipulation library called Obscura.

t all started with the arrival on the scene of microjs.com by Thomas Fuchs and Dustin Diaz. For those of you who haven’t heard of it, microjs.com is an index of micro frameworks curated by Thomas and Dustin. The requirements for inclusion on the site are as follows:

  • Must be written in javascript
  • Must be less than 5k minified and gzipped
  • Must be focused on one thing, rather than being a library of all trades
  • Must have no dependencies

I liked the idea of this and was keen to get a listing on there as a step towards my goal of becoming more known in the community. Unfortunately none of my previous projects met the requirements, so if I wanted in I needed to come up with something else. I’d seen a tutorial in .Net magazine on image editing using javascript and canvas and decided I could port my existing PHP ImageHandler class to javascript using canvas as a base.

I also decided to use this as an oppurtunity to try out CoffeeScript which I’ve been hearing a lot about. Once again, for those out of the loop, CoffeeScript is a lot like Sass, which I’ve mentioned previously, but for Javascript. It’s a language that compiles to javascript, so you can write your code in CoffeeScript’s clearer, more verbose syntax, then compile it to normal working syntax.

I’m not normally a fan of stuff like this as I’ve never really seen the point, if you want to write javascript just learn javascript. However both Sass and CoffeeScript have convinced me that there are benefits to these things. In the case of CoffeeScript the automatic handling of things like scope and variable declaration make developing a lot easier and safer. The automatic wrapping in a function did cause me some confusion at first, which I’ll discuss later, but does prevent any unnecessary pollution of the global scope and can be turned off with a compile option. I am however still adjusting to the braceless syntax which I’m not too keen on. I appreciate that it makes the code cleaner and smaller but as a php developer predominantly I’ve grown used to curly braces or at the very least some kind of ruby-esque closing statement.

I decided to stick with a small selection of basic image manipulation functions to start with. As I was using my existing PHP library as a starting point I had a ready supplied list of functions to use, with the basic logic all worked out. All I needed to do was work out how to write the functions in CoffeeScript and understand how to apply them with canvas. The latter proved to be the more challenging task for the most part. Particularly due to the inconsistencies in how the W3C’s canvas spec is implemented in Gecko and Webkit. The main issue I came across was when working on the rotate function. I had been using the globalCompositeMethod copy to overwrite the existing canvas data which worked fine in Firefox but in Safari and Chrome “copy” actually overlays the new data onto the old, so the original, unrotated image was still visible. I ended up having to create an internal canvas object as a kind of staging area so all manipulations were performed on that before the finished article was sent to the target canvas.

By far my favourite CoffeeScript feature when writing this was the way it handles scope and the ability to reference the parent object easily when writing the code made life considerably easier, particularly as all the functions perform operations on internal objects. For any of you who haven’t played with CoffeeScript yet or aren’t familiar with the scope handling, it works like this:

Which will compile to this

Notice that CoffeeScript adds the __bind function which is then used to make sure the function executes in the object scope. Granted you can write this yourself but the syntax of the CoffeeScript is a lot simpler and clearer as to what is going on.

After a few weeks of playing around I got Obscura into a state I was happy with for a first version release. It passed all the tests for inclusion on microjs.com, coming in at 1.5K compressed and gzipped, so I submitted it for inclusion and got it accepted. Obviously I was pretty pleased about this as it was one of the main reasons for writing the library in the first place and it was great that my work was considered good enough to be accepted onto the site but it didn’t stop there. Later in the same week I got an email from Softpedia informing me that one of my projects had been added to their Scripts section. At first I had no idea what they were talking about as I hadn’t submitted anything to Softpedia.Upon further investigation it would appear that they’ve been scanning other websites and finding libraries and widgets to add to their new Scripts download section. The project they’d added was Obscura so what I’m guessing has happened is they’ve been scanning through microjs.com and adding projects from there. It also appears they’ve been using those projects as starting points to find other projects as throughout the day I got more emails telling me they’d added other projects that are on my blog and github account. By the end of it 7 of my projects had been added; Obscura, Uncharted, Zebedee, ermintrude, Easel, tipBox and Delorean. For me this was a huge breakthrough in terms of what I’ve been trying to achieve this year as it’s providing more avenues for people to find out about my work and hopefully use it and help improve it. It’s also resulted in people starting to watch my GitHub repositories so hopefully I can build on this and keep raising my profile as the year goes on.

For now feel free to check out Obscura on GitHub for the code and demos

Obscura | Demos

Tool Tips, Javascript Animations and Coding Without a Net

I’ve been working on overhauling the UI experience in the back end systems we use at work and decided that I wanted some tool tips to help tell users what things do without them having to ask us. The only decent tool tip library I’ve ever found was Prototip by Nick Stakenburg but I knew I wouldn’t be able to get away with buying a license for it so I needed to create my own. After my experiences doing the emile.js version of zebedee I decided to give myself a bit of a challenge and go completely frameworkless to create a standalone widget.

First up was finding out how to do encapsulation in javascript so that I was only giving access to the methods that needed to be accessible from outside the class. The way this is done is to return an object with the public methods defined in it, rather than doing return this. For purposes of scope I defined the methods before the return statement, then returned references to them. Like so:

Once I had that that figured out it was down to creating the various methods and setting up the event listeners. The main requirement was handling the positioning of the tool tip in relation to it’s trigger element. As the position could either be fixed to a point on the trigger or follow the mouse, I ended up creating an object with either the element properties or the mouse coordinates and using that as the starting reference to perform the calculations from, then scanned the position option for one of the y position possibilities and set the top and did the same for the x position options. I later expanded this to have an optional element passed through which would be positioned instead of the tooltip, for use with the animations.

I spent a lot of time going through prototype and zepto to find out how to do the various things I needed to do without the frameworks and ended up stealing various little bits of code, like the user agent regular expressions from zepto so I could determine whether the browser was running webkit, I also tweaked this to check for gecko 2 as well. This was so I could use css animations where available for the transitions. When it came to dealing with the animation, emile.js ended up being my main source of reference, to the point that when I needed to expand my original animation function to be more flexible I ended up taking emile’s animation code and a few of it’s helpers and tweaking them for my own purposes.

The biggest challenge with doing the animation was the scale transition and positioning it, particularly the css animations. With the javascript animation it was easy to make the box appear to grow and shrink from it’s trigger element, as I just needed to call the position method each time I adjusted the size. But with the css couldn’t call anything on each iteration so I had to create a test element that was a clone of the tool tip, alter that, reposition it and get the end values, to then pass through to the animation function. In the end it worked out but I’d like to play around with it to see if I can get something less long winded. I also want to have a play to see if it’s possible to make the text grow and shrink with the box, by using ems. Another interesting thing I discovered while working on the CSS transitions is that both Gecko 2 and Webkit have their own version of the transition end event, in Gecko 2 you can use transitionend but in webkit you need to call webkitTransitionEnd. Also this event will get called for each property you are animation, so in the case of the scale transition,where I was animating width, height,left and top, the event was being called four times. Remember to check for this when writing your handlers.

I ended up namespacing the tool tip function inside a tipBox object, so I could add the scan method and keep them together. This means that while the calls are a bit longer, the functions are kept neat and secure, and shouldn’t conflict with anything.

The scan method enables you to have a load of elements on a page (preferably a tags for semantic reasons) with a given class name that you can turn into tipBox triggers with one function call. All you need to do is pass the class name and the options you want to use to the method and it will scan the page and set up the tipBox for each one, using the title attribute to supply the text.

I found getting the initial stages of the widget working were a lot easier than I expected, which I take to be a good sign that my understanding and knowledge are improving (either that or it’s easier than I thought and I’m just being a numpty). The animations presented my biggest challenge and took as much time to work round as everything else did to create but were without a doubt the most rewarding part of it to complete. The whole coding without a net approach forced me to explore and learn more, and work out my own solutions to how to do things, which was great fun, and will hopefully result in an improvement in my javascript work from now on.

Code and demos are available on GitHub:

tipBox | Demos