Author Archives: John Munsch

Byte Magazine December 1980

When I read a book like Fire in the Valley it’s a trip to my very early teen years. I had zero money with which to buy a personal computer but I was completely obsessed with them. I don’t recall for sure whether I actually had my first computer yet at the time that the December 1980 issue of Byte Magazine came out, but it was probably pretty close to around that time. It was an unusual issue for them because it focused on computer games (specifically Adventure games of the type that Scott Adams sold but there was plenty more in the issue than that). I know that I must have checked out that one issue half a dozen times from the periodicals room at the Fort Worth Public Library downtown so I could read through it.

If I didn’t have it yet, I did get a computer within a year or so because I would split the price of a TI 99/4 with my best friend Stephen Watkins.

Just recently the Internet Archive made available the entire run of Byte Magazine so you can download anything you want to see about what computing was like from 1975 to 1998 but I naturally gravitated to the December 1980 issue just to see what it was I was looking at 33 years ago.

  • Everything that’s easy today is difficult then. Buying software, storing your files, communicating with other people, displaying color graphics, and printing are all very difficult. You need to buy special hardware or software and hook up a crap-ton of stuff yourself or hire somebody by the hour to figure it out for you. OK, you’re right, printing still sucks 33 years later; but it used to be worse.
  • They’re all out of business. This issue is 400+ pages of gravestones with Apple and Radio Shack being some of the only survivors (and I’m not sure about Radio Shack lasting another 33 years). Microsoft, Sony, Seiko, and HP all make appearances in other people’s ads but basically every hardware manufacturer, computer store, and software maker here is gone gone gone.
  • It may not have much more RAM but the $9 Arduino I just bought is basically a super fast Apple II on a card.
  • My thought that you couldn’t do much with 32K should clearly be re-calibrated, we did everything with just that much room once upon a time.
  • Is that really a wiring diagram for building your own video board in a national computer magazine?!?
  • We just devoted several pages to a Basic language game listing that doubtless would have only worked for one model of computer. Everything about that is archaic.

So go download your particular tidbit of nostalgia and try to imagine what a computer magazine of today would look like to you in 2046.

Just enough server (and no more)

I’ve reached a point where I actually want very little from my app server. My requirements for a web server are the antithesis of the hulking monoliths that dominate the Java EE world because all I want is:

  • Something that delivers my static files (HTML, CSS, JavaScript, images, maybe later things like video/audio).
  • Something that can handle HTTPS encryption. Compression is nice to have too, but not an actual requirement.
  • It would be a huge help if it offered some way of handling authentication and then validated it on a variety of paths (somehow this usually gets skipped in the big app servers as very important).
  • It can support my building of an API so my client (which at the moment is AngularJS but could just as easily be Ember.js or Backbone.js) has a back-end to which it can connect.
  • Offers some way for the API to be able to connect to some form of storage to retrieve and persist data, probably by connecting to a database or NoSQL solution.

If you give me just that from a server you’ve given me enough to build a lot of different kinds of applications. Not all of them, but probably a majority.

Note that the first two requirements I mentioned above aren’t even strict requirements. If I put Apache’s web server in front of the app server then I can handle serving up the static files or HTTPS encryption and the app server is needed even less. But for the purposes of easy setup for software development it’s nice if the app server can stand alone for a while without requiring Apache.

That’s why I’m pretty excited about Node.js at the moment. It’s an example of “just enough server” because you can configure a server, seemingly very simply, that will do just that handful of things and no more. Now, this is the classic example of having read about something but not having actually done it yet. I haven’t built anything of any real size with Node.js yet so once I really get in there I may completely change my mind about it. But I’m keen to see if I’m right and it can be that for me.

Follow Up

I’m just so clever I’m pretty much a complete idiot. More than a week ago a friend of mine at work pointed out a new course on MongoDB and said, “You should take that, you’ve been talking about that and it’s free.” Since having a JSON document based storage to go with Node.js is a pretty natural fit, I promptly signed up for 10gen’s course M101JS MongoDB for Node.js Developers and then I equally promptly… forgot all about it. But writing this entry yesterday jogged my memory a little and I thought, “Hey, I should go check out that course, I can start watching the lectures and maybe catch up to everybody else.”

So I went to check it out and discovered that there were lectures I hadn’t watched but better than that, it was a course with a grade, and it was a course with homework too. Yay. Fortunately, while the lectures took a while the homework took only 15 minutes or so for the first one and I’m all caught up. So maybe once this course is done, you can join their next one if they offer it again for free. But try to remember your homework.

Yes it’s “REST” but is it any good?

I’m not picking on the author of this discussion of different levels of REST APIs. As a matter-of-fact, I thought it was a quite good article. But the advice I see over and over again for how to build remote APIs seems focused on the URLs and how they are formed as a function of whether the API is “good” or “bad”. So let me just say this… If your API has you performing atomic units of action via multiple API calls to the back end, your API is bad whether it conforms to all the REST requirements or not.

So, if you’re taking money out of one account via one call and then transferring it to another via another call, you’ve:

  • allowed business logic to leak into code outside the back end
  • created a situation that is almost guaranteed to result in a corrupted database, keystore, or whatever at some point
  • made anyone using your API work much harder (for example, if after adding a new user, they also need to go add that user to a group, add an avatar picture, etc. all as separate operations)

One alternative I would recommend looking at (I’m not advocating this as some kind of REST replacement, just something you need to take ten minutes to learn about) is CQRS. The link is to a warehouse of info on it but the basic idea is that an API will have queries where you just get data for display and commands (think Gang of Four Command pattern) for performing actions in the system. Thus moving money from one account to another might be a command or adding a user might be another. In each case, you’ll provide enough data with the command to make sure the back end can completely perform it in one atomic operation and the front end stays out of the business logic/sequencing business.

I’ve yet to read the grand treatise on how to create a great CQRS API which runs on REST. I’d love to read such a thing if you find one. Please leave a comment below if you do.

AngularJS Services and Promises

Promises, Deferred, Futures

Call it what you will, promises are another mechanism for dealing with the asynchronous nature of some things you’ll do within JavaScript. For example, calling remote services, timers, animations completing, etc. In each case you could just have a callback, but what if you wanted to attach several callbacks to the completion or failure of a single asynchronous job? That’s difficult with callbacks, but promises make it easy.

Promises make it easy to tie together several asynchronous actions and treat them as one. This makes it easy to react only when all have completed or one of them had a problem. This is a much better solution than the nesting of callbacks you often see done in JavaScript code. Nested callbacks are often written in a way that forces requests to be made serially when they could be executed in parallel and perform better as a result.

Promises can simplify code in another way because a promise which has already resolved and one which has yet to resolve are treated are both used in exactly the same way.

Promises in AngularJS

AngularJS offers promises via a service called $q. It is modeled after a promise library called (not surprisingly) Q. You’ll see promises returned from several of AngularJS’s services, including $http (for service calls), $timeout, and $route (though I admit I’m not sure how it’s being used in the latter case).

AngularJS even has support for promises being assigned directly to $scope variables. So you can take the promise you get back from a remote service call and assign it directly to a variable knowing that when the service call finally returns, the variable will be updated and any binding attached to the variable will redisplay. That’s significantly easier than other frameworks I’ve used in the past.

Service Calls

I thought I’d give three examples of calling a service with $http and show how the promise it returns may be used directly, and examples of how caching and aggregation can be made easier thanks to promises.

For these examples I’m just calling the OpenKeyval service to store and retrieve some JSON data. It’s simple, it’s free, and I know I can count on any code I give you being able to access it without any special API key.

Source code for all of the following and more is here: https://github.com/JohnMunsch/AngularJSExamples, in particular look at the app/scripts/controllers/promises.js and app/view/promises.html to see the code specific to these examples.

Click here to see all of the following as running examples on Github

    • Example 1: Store and retrieve some values. Promises returned from $http are assigned directly to $scope variables and AngularJS dereferences them automatically.
    • Example 2: Make multiple calls to different services aggregating the results of all the calls and merging the results into a single returned value.
    • Example 3: A common pattern for services is to be able to satisfy requests from a local cache when appropriate. Promises can make that an easy upgrade for an existing service.

A Shortcoming

$q is not as full featured as Q is. That’s not surprising because AngularJS is only trying to provide as much functionality as it needs without requiring you to load up another library. AngularJS does the same kind of thing when it comes to jQuery. It has a minimal subset of functionality built in (called jQLite) that it uses if jQuery wasn’t loaded prior to loading AngularJS.

However, this is where things suddenly differ. If you do load jQuery prior to loading AngularJS then it won’t use it’s own built in version, but will instead use the more full-featured jQuery implementation. However, as far as I know, loading up the Q library or jQuery before you load up AngularJS doesn’t cause AngularJS to use Q promises or jQuery Deferred objects instead of its own subset implementation. That seems to me like an oversight or shortcoming to their implementation.

Nevertheless, I hope I’ve shown with the examples above that you can still do some really interesting things even with the limited set of functionality $q provides.

Follow Up

After a few weeks I realized that something I didn’t really cover is how assigning a promise to a variable in $scope can hinder access of that same variable in the controller. For example, if you do something like this:

$scope.someValue = $http.get(someURL);

You’ve assigned a promise to the variable and from the standpoint of code in your view, nothing really changed. You can still do {{someValue.someSubValue}} and act blissfully unaware that someValue is a promise rather than a JavaScript object. But, try the same thing from the controller code and you’ll have all kinds of problems. $scope.someValue.someSubValue isn’t anything you can access in the controller because $scope.someValue is actually a promise and will always stay a promise, even once it’s resolved. The only thing that changes once it’s resolved is that any .then() function you call on it will immediately call the closure you pass into it with the value the promise now caches. Thus you will forever more have to use it within the controller like so:

$scope.someValue.then(function (value) { $log.info(value.someSubValue); });

If you have some values you’re getting via AJAX calls or via some other mechanism that returns a promise and you need to access them as much or more from a controller as from view code then only assign the resolved value into the scope and not the promise. For example:

$http.get(someURL).then(function (value) { $scope.someValue = value; });

In that case you’re waiting until the promise resolves and only assigning the final returned value into the scope. Now both the view code and the controller can directly access $scope.someValue.someSubValue freely.

Reference

Yeoman, Grunt, and Bower

Aside from being a top end legal team, Yeoman, Grunt, and Bower are also the names of some front-end development tools I use when working on new projects these days or whenever it’s going to be easier to throw together some code and test it out in a testbed rather than embedded in a larger project. First I’ll go over what role each of these has in the development of a modern website front-end. Then I’ll take a brief side trip into a tool (Node.js) which isn’t directly relevant to any of them, but one which is required in order to install them. Then we’ll get into some specifics for all three as I demonstrate using them to get started on an AngularJS project.

Yeoman is the code generator, it fulfills a role similar to that filled by the Rails app if you’ve ever used Ruby on Rails because it can be used to generate whole projects or individual pieces of code depending upon the specific code generators it has installed. It gives you a quick shell from which to start a project.

Grunt is the builder and utility tool. As with Yeoman it’s modular in nature and as a result it can fulfill a huge variety of roles. Typical things you might call upon Grunt to perform would be concatenating multiple CSS or JavaScript files together for faster download, minifying CSS or JavaScript files (again for faster download), running a small local server to make developing your website easier, looking for errors in your JavaScript, running JavaScript unit tests, running compilation tools for CoffeeScript, LESS, or Sass, and the list goes on and on. If you have a Java background you might think of Ant as the closest analogy for Grunt.

Finally, Bower is your web component installer. If you find yourself needing to install a JavaScript library or a CSS/JavaScript framework, Bower can handle that and even make sure that any other components upon which it depends (for example, Backbone.js requires Underscore.js) are also automatically installed. Java tools like Maven and Ivy offer similar functionality so that each developer can get the libraries he/she needs installed without having to check all of them into version control systems with the code being developed.

That side trip I mentioned

As strange as it might seem to require an installation utility (npm) in order to install an installation utility (Bower), that’s exactly what I’m going to tell you to do. These days any JavaScript software worth its salt seems to be installed in much the same way. First you go get the latest version of Node.js (there’s a big green install button on the middle of the http://nodejs.org/ page). When you install that you’ll also pick up a nifty little utility known as the Node Package Manager or npm for short. With npm installed you can then install all three of the aforementioned tools Yeoman, Grunt, and Bower.

As I mentioned earlier, you use the npm tool you just installed to install the other three by running “npm install -g yo” (the details are covered on Yeoman’s website: http://yeoman.io/ but that’s actually all you have to do). You’ll see npm download, compile, and install tons of stuff but you won’t actually be involved in the process. In that respect it’s much like other package managers like Yum or RPM.

Finally you’ll need some kind of Yeoman generator installed in order in order to generate our starting shell: “npm install -g generator-angular”

Yeoman

With all the installation out of the way, let’s create a directory for a new project (“mkdir TestApp”), change directory into the newly created directory, and just type “yo” at the command line and see what we see.

YeomanPick “Run the Angular generator” and hit enter, then answer the various yes or no questions it asks in order to generate the shell you want for your app. At the end it will also run npm to install the local copies of tools you may need and Bower to install the various libraries you need for your shell (for example, AngularJS and jQuery).

Yeoman has now fulfilled most of its mission but I want to look at some files it generated and then come back to using it as a tool even after we have our shell. There are many files worth noting which Yeoman generated but three in particular are:

  • package.json – This file tells npm which Node.js packages need to be installed in this particular project. Most of what you’ll find in here are packages Grunt needs to do its job. Rather than installing these globally, they are instead installed on a project by project basis so you can have different versions of the tools used by different projects.
  • bower.json – This file tells Bower which components to install in the app/bower_components directory. These are JavaScript and CSS components which you’ll use within the website you’re building.
  • Gruntfile.js – This file is task instructions for Grunt so it knows how to perform a set of different tasks for a given project. If you look near the bottom of the file you’ll see that the Angular generator has created a file with the tasks “server”, “test”, and “build” which in turn call many other sub-tasks to perform their work.

Finally it’s worth noting that that’s not the final use that Yeoman can have in our development. Just as a Rails user can continue to use the Rails command to generate new models, migrations, etc. within an already constructed project, the Angular generator can be used to generate services, routes, directives, filters, etc. as detailed here: https://github.com/yeoman/generator-angular

Grunt

Running Grunt from the command line with “grunt” should perform a default sequence where the JavaScript code is checked for errors, unit tests are run, and finally a “distribution” version of the application is built into the “dist” directory. Grunt will have concatenated CSS files and JavaScript files into common chunks like 7d151330.main.css, bd6ce9e3.plugins.js, c2ac0a01.scripts.js and the references to the original names within the HTML will have been replaced with the new file names. When you update some of your scripts and recompile, the file names will be different and there will be no need to worry about browsers continuing to use old cached versions of your scripts. You never have to perform this task, all of the files within the app directory may be deployed as soon as you are ready to do so, but Grunt performs a variety of optimization tasks which can make for a more performant site if you like.

One of the handiest things Grunt offers via the Gruntfile.js which was created is “grunt server”. Running that will compile files which you might have that need compiling (for example, if you use CoffeeScript rather than JavaScript or you’re using Sass), start up a server running the application, launch the index.html page in your default browser, and then watch for any changes to the files as you edit the CSS, HTML, and JavaScript and re-run compiles as needed and reload the page within the browser as you work on the website. I just love this feature because of how easy it makes it for me to work on features and immediately see the results in my browser, often I don’t even have to lift my fingers from the keyboard or switch apps to my browser because I can see if my changes accomplished what I want simply by looking at the automatically refreshed page.

At this point you would be forgiven for thinking that there was little point in installing Node.js except that it gave us the npm tool we needed to install all our other software, but actually Node.js is also being used behind the scenes by Grunt to run the local server I mentioned above.

Bower

Last but not least is Bower. It offers the opportunity to search for packages you may need in your project (for example, “bower search underscore” to find Underscore.js) and install them in your project (for example, “bower install –save underscore” to install the aforementioned package and add it to the list of dependencies in the bower.json file). Bower is also capable of understanding the difference between packages needed for development (for example, unit testing tools) and those needed for both development and runtime.

Since the .gitignore for the project will normally list both the app/bower_components and the node_packages directory, you won’t be checking in those pieces with your code (assuming you use Git as a version control mechanism). Instead, whenever checking out the project onto a new machine, just run “npm install” and “bower install” within the project directory and the tools will use the package.json and bower.json files to make sure all the needed pieces are installed.

But that’s not all

Keeping these tools up-to-date might prove difficult if not for the fact that the Node Package Manager is capable of doing so automatically via “npm update -g” for all your global software like Yeoman, Bower, etc. or “npm update” within the project directory to update Grunt packages, etc. I’m not going to contend that it always goes flawlessly, lots of this software is still beta and undergoing lots of changes so there have been days when I needed to remove it all and reinstall; but that’s rare and usually takes only a few minutes.

Changeable vector graphics with SVG and AngularJS

I’ve long been a fan of using SVG (Scalable Vector Graphics) to do images that I can change easily on the fly. When I say “long been a fan” I mean that when I first started doing it I hand wrote some SVG as XML to show a donation bar we needed for GameDev.net and I had a program that would change the amount thus far donated on the bar and run it through an early version of the Java Batik library to spit out a JPEG file we could put on the website. It was crude, but it sure beat making a new graphic two or three times a day.

Years later things have gotten a lot easier. Modern browsers have advanced to the point where you can include an SVG image in the page as easily as referring to them in an img tag like so, <img src=”something.svg”/>, or just dumping some SVG code straight into the middle of the HTML for your page like this <svg>…lots of vector graphics…</svg>. And editing? Why would you edit by hand anymore when Adobe Illustrator can generate SVG files of your drawings for you, or if you have no budget for such nice tools, Inkscape does a pretty good job and costs nothing.

So it occurred to me the other day that it would be interesting to see if I could use AngularJS and its ability to rewrite HTML on the fly and combine that with SVG in the browser to rewrite SVG on the fly. The answer is, it not only works, it’s downright easy to do so. I’ve provided a couple of different examples to show just how easy it is to so.

Example 1: Have a SVG graphic where I change text within the graphic automatically because it’s tied to a value in an AngularJS model.

Getting an image to start with was pretty easy. I went to The Noun Project and grabbed an icon of the sun I liked. It was provided by an unknown author in this case. The icon came in SVG format so all I did with it in Inkscape was add a little color and some text that showed the temperature. Then I saved that as a “Plain SVG” file rather than an “Inkscape SVG” file. It might have worked as well with the latter but I didn’t want any surprises.

Inkscape editing SVG icon

I then popped over to an HTML file I had generated and imported it with an image link like this:

<img alt="" src="images/sunshine_plus_temp.svg" />

I then hand edited the SVG file and found where the text for the temperature and replaced it with an AngularJS model variable reference. So:

<tspan sodipodi:role="line" id="tspan4542" x="97.124313" y="52.063747">87°</tspan>

became:

<tspan sodipodi:role="line" id="tspan4542" x="97.124313" y="52.063747">{{temp}}°</tspan>

The <img> way of loading the SVG had to change because AngularJS wasn’t going to replace a variable inside an image for me. So I simply pasted the contents of the sunshine_plus_temp.svg right into the middle of a page already setup for AngularJS and put the temp variable into my $scope. It worked like a charm. With an input field tied to the model variable, as I typed, the SVG graphic was automatically updated with the new value.

My final touch was to externalize the SVG file. Nobody wants to edit an HTML file with half a dozen or more embedded lumps of SVG in there. It could quickly turn into an unreadable mess. And, as I already observed, <img> won’t work either. Ah, but AngularJS jumps to the fore again because it has it’s ng-include directive. All I had to do was this:

<span ng-include="'images/sunshine_plus_temp.svg'"></span>

and AngularJS was including the image where I needed it and binding the variable to the model for real-time update. Here’s the final version of the code I came up with for my first example, note the second set of quotes inside the ng-include to tell it not to interpret the string inside there, it’s just a string to use directly:

  <div>
    <p>Example 1: Text updated on the fly in an SVG graphic via AngularJS.</p>
    <span ng-include="'images/sunshine_plus_temp.svg'"></span>
  </div>
  <label>Temperature</label> <input type="text" ng-model="temp"/>

It’s worth noting that Inkscape is still perfectly capable of editing the SVG file even after the change I made and I guess I could have just made the change within Inkscape in the first place and never bothered opening up the file to manually change it with a text editor.

Inkscape editing modified SVG icon

Example 2: Have an SVG graphic that incorporates an image (just because it’s vector doesn’t mean it has to be all vector, SVG is great with images too) and use AngularJS to swap out the images on the fly.

We don’t really need a second example here, the first one showed pretty much everything but I wanted to show how easily images incorporate into SVG and help you achieve results that would be much much harder to do with other techniques. In this example I took a slides icon by Diego Naive, from The Noun Project, overlaid an image on top of it, and then overlaid a glossy reflection on top of half the slide, just to show that the image is fully incorporated by the graphic and can easily be rotated, have graphics on top of it, underneath it, etc. Stuff that would require a lot of work to do with many other techniques.

Again, I tested it out and edited the final SVG file to add a variable reference, in this case to {{slide_image}} instead of the specific file reference that I had added with Inkscape. This time, I will say that it does not edit nearly as well in Inkscape after the edit because it doesn’t know where to find an image named “{{slide_image}}”. Within the Inkscape editor you just see an error box where the image should be. Not perfect, but not debilitating either.

Here’s a page with links to both examples and to the Github repository with all the code for both: http://johnmunsch.github.io/AngularJSExamples/

Explaining closures to a five year old…

Once upon a time, someone on Stack Overflow asked the question, “How to explain Dependency Injection to a 5-year old”

The author of the question was really just looking for a good simple explanation but the title had resonated with people and I was surprised to see that person after person had either declared it impossible or had made a snarky comment about child abuse or something. But the answer was really obvious so I posted my answer: http://stackoverflow.com/questions/1638919/how-to-explain-dependency-injection-to-a-5-year-old/1638961#1638961

And I got more up votes than for anything I’ve ever answered before or since. So when I was asked in a recent job interview if I could explain dependency injection, I laughed, and then I explained why I laughed and what my answer had been. Then later in the interview I was suddenly thrown a new one, “Can you explain closures? No wait, can you explain closures to a five year old.” I have to admit, I vapor locked. I could not come up with an answer that a five year old could possibly understand. To me closures have three elements you have to talk about if you want to explain them (or at least how they are in JavaScript which is where I have the most exposure to them). They are, a repeatable set of code that can be handed around and called in different circumstances, a set of variables which were bound when the closure was created, and another set of variables which can be passed into the closure so they are different every time it is invoked. So I did explain it at that level and the interviewer was pleased, at least to the extent that I got the job.

But I couldn’t let that drop, so I thought about it and it occurred to me that there was a pretty good analogy in a child’s life to closures. So I wrote it down and sent it to the interviewer the next day, and maybe that’s why I got the job after all. But anyway, I give you closures for a five year old…

You know how you like to play Star Wars*? I know what you mean when you say you’re going to go do that and I can tell you to “go play Star Wars” and you understand me.

You can play it in different places, like over at Jimmy’s sandbox and it will be Star Wars on Tattooine or in your big box that is Jabba the Hutt’s palace, but you can always have your Luke Skywalker, Han Solo, and Darth Vader with you so that part stays the same as when you first played it in your own room.

*Substitute Barbie if you prefer.

Can you do JavaScript development with just an iPad at hand?

I recently headed off on a five day vacation and though I do have my priorities in order (eat, see the sights, take photos, walk a lot, read a lot) there is inevitably some downtime as the days go on. I didn’t want to lug along a laptop on this vacation so I resolved to see if there was any practical way to play with AngularJS and Ember.js (two frameworks I’ve been interested in recently) using only my iPad and an inexpensive Bluetooth keyboard.*

iPad and Bluetooth keyboard

For those who wish to skip ahead, the short answer is that it is possible, but it’s not much fun figuring it out so I’ll tell you later how I did it. As for whether it’s practical, I don’t think I’d consider it for anything except a small test project and the reason why comes down to one simple thing: debugging. If you’re a modern JavaScript developer you’re used to wonderful tools like Firebug and the Chrome Developer Tools for debugging and while Safari on iOS once had access to some basics like the JavaScript console those have been removed from iOS 6 in favor of a new remote debugging method. The new solution relies on a remote connection to Safari on Mac OS X. I’m sure it’s a much more sophisticated solution but why did we need to lose all JavaScript debugging support on iOS to get it? If I have to have my Mac along to do debugging I might as well do the JavaScript work on OS X in the first place…

That leaves your only debugging option as Firebug Lite 1.4, a project which has basically been abandoned due to lack of funds or interest or something and when I tried to combine it with AngularJS I was never able to get it to appear within the browser. I had more success with Ember.js because it both appeared and showed all the console messages from Ember, however the script tab was unable to show me the contents of any of the JavaScript files I was including locally. Due to the slow performance of the wi-fi at my hotel I pulled firebug-lite.js, jquery, handlebars, ember, etc. all down to my iPad and put them in the same location as the index.html file and the main.js file I was editing. Due to some form of security restriction with how the files were being loaded into the local browser Firebug Lite was unable to show any of them to me.

Ow.

That means that you’re going to be flying completely blind with AngularJS unless you’re prepared to handle logging via some other mechanism and even on Ember.js, are we really looking forward to something that’s reduced us to debugging entirely via log messages?


Textastic

I promised that I would say what I found worked best for development work and it was Textastic. It will let you create directories, fill them with files, edit them, and then view them with a built in instance of the iOS browser. It’s simple and straightforward and I was able to paste in sample AngularJS and Ember.js pages and they worked just great. I just couldn’t ever debug them properly. It does cost a few dollars but if you’re just looking for some easy way to play with HTML, CSS, or some simple JavaScript when all you have is an iPad (and hopefully a paired keyboard) then it’ll do in a pinch.

BTW, Cloud9 IDE looks like it would be an even better solution to this problem but they use the Ace editor and for whatever reason, it doesn’t work well on an iPad. I had problems with cursor position being one place while actual editing was another, it didn’t want to work well with my keyboard, it seemed slow, etc. There needs to be some work done on either the editor itself or on the iPad browser (or perhaps both) to make that a more viable solution.

Textastic - Ember.js plus Firebug LiteP.S. Most of this blog entry was written on the self same iPad/keyboard so don’t think the iPad is useless for any form of content creation, it just doesn’t do software development well at this time.

* Specifically a third generation iPad and the AmazonBasics Bluetooth Keyboard.

What I learned from… Ruby on Rails

After I read the excellent article 4 Things Java Programmers Can Learn from Clojure (without Learning Clojure) I not only took in the interesting lessons the author had, but I was prompted to think about all the lessons I’ve learned over the years from the various frameworks, languages, APIs, projects, and people I’ve worked with.

So, in the interest of starting a series which I may or may not update periodically, here’s the first installment of “What I learned from…”. I decided to start with the single framework I spent not that much time with (off and on for a couple of years) but from which I learned more than any other; Ruby on Rails.

Here are five things that I learned from Ruby on Rails:

1: A holistic approach can be wonderful

A lot of frameworks and languages end up just being a big bucket of parts from which you can pull to assemble your own development platform. What ends up happening is that every business ends up with their own variant on that mix.

Rails is often referred to as “opinionated”. In practice that means that they make decisions for how things will be, whether its file formats, or directory structure, or the libraries which are included as standard. They try to come up with a solution that will work 80% of the time for every need a web application developer typically has and then wire that up as the standard in the framework. However, in many cases they have put in work to ensure that you could replace a given piece if your app is one of the 20% for whom that particular solution isn’t a good fit.

2: All the “extras” as standard

This is kind of saying the same thing as my comment about a holistic approach, but lots of other frameworks I’ve worked with skipped huge swaths of problems and yet still seemed to think of themselves as “one stop” solutions. Rails saw that you didn’t really have a solution unless you had addressed package installation, testing, different deploynment environments, database changes, etc. Here are three big ones that are either usually skipped or which didn’t get much attention until post-Rails.

  • Testing – No, testing isn’t really optional. It makes your code better and it costs very little once you get over initial setup costs. Any effort put in by the framework to make it easier is time spent that multiplies tens or perhaps hundreds of thousands of times as it encourages people to improve their projects.
  • Environments – This is such a basic thing that I’m astonished how few frameworks deal with it. Virtually all software is run in development mode with different settings than in production. Even if those are your only two enviroments (or if you have others like test and beta), you can benefit from having support for different configurations and setup that are per environment.
  • Migrations – Although there are some third party Java libraries (Flyway, LiquiBase) that try to offer the same kind of functionality, I haven’t seen Rail’s concept of a series of updates which can take your database to the latest version to match your code (or backwards when needed) take off nearly the way a lot of other early Rails stuff seems to have been adopted elsewhere. I think just about every app development framework which deals with databases would benefit from it and I’m always surprised this one hasn’t spread more, though I noticed a recent Kickstarter to add them to Django.

3: Convention over configuration

If you’ve ever worked with Struts then you’re familiar with files that have to be filled in with data every time you add a new page to an application. Rails avoids that by simply saying, “Put this type of file in this directory and I’ll know, by convention, what you want me to do with it.” In many cases it can use the name and location of a file to know everything about how to hook it into an existing application.

There are people out there in your career who will try to convince you that having a file (or in some cases, many files) you have to edit are better than simple conventions. That they allow you “flexibility” and you can put your files anywhere you want. Do not listen to those people.

4: Proscribed directory layout

Simple test, take a random open source Rails project out of Github and a Java one. Try to find stuff and quickly understand each of the two projects. The Maven proponents would claim that adopting Maven gets you that same kind of structure to your project for Java and I don’t have enough experience with it to agree or disagree. But my experience with regular Java projects tells me that each one is a “unique little snowflake.”

5: method_missing

This is actually a Ruby thing and not a Rails thing at all, but Rails gets lots of mileage from it.

method_missing is a method that gets called whenever a method gets called on a Ruby class that doesn’t exist. However, you can implement method_missing yourself and you get full information on what the code tried to call. Rails uses that in ActiveRecord to synthesize new functions on the fly to keep the syntax of their ORM system ridiculously simple. For example, “Person.find_all_by_name(‘John’)”. Is there really a find_all_by_name? Nope. Can it create one on the fly based on the name of the function you called? You bet.

It seems like method_missing is something that would only work in a dynamic interpreted language like Ruby, but I’ve long thought that you could create a completely compiled language that would be capable of synthesizing new functions like this at compile time as well. The benefits are largely in the area of ease-of-coding but they are real ones. For example, why bother having getters and setters on your classes if they could be synthesized automatically?

I’m not sure where I’m ever going to use a language construct like this again unless I somebody asks my advice about writing a new language, but I’m storing it away. You never can tell when something like that will come in handy.

Easy background images for your iOS views

On an iOS game I’m developing I wanted a background image on some of my views. That’s an easy thing to do in the interface builder by simply adding a UIImageView stretched to the full extents of its containing view. However, I’ve layed it out for the four inch form factor of an iPhone 5 or the equivalent iPod Touch, how will it react to the form factor of an iPhone 4, 4S, or the older Touch?

The answer is that thanks to Auto Layout your controls can be made to adjust quite nicely, however, you’re going to have some issues with that image. By default the image view adjusted its size to the size of the containing window and squeezed my background image. Ick.

The fact that you may have two versions of the image, one Retina and one not (that is, background.png and background@2x.png) doesn’t save you because there are older devices that have both Retina displays and smaller screens. What you need is a solution that works with 4″ Retina, 3.5″ Retina, and 3.5″ non-Retina screens.

The background.png isn’t an issue. It should only come into play for non-Retina screens and to my knowledge there are no four inch non-Retina screens. Go ahead and just lay it out for 320 by 480 and be done with that one. Then, if the background is one where you can design a version that can safely lose 176 pixels in the long dimension (via a border or other area that can be safely clipped), then lay out a background that is 640 by 1136 with 88 pixels at the top and bottom that will be clipped off when it is viewed on the smaller screen. Then you can change one small setting on the image view so it will center and clip the image rather than squeeze it and you’re done.

The background image as it would appear on an iPhone 5 (640 x 1136).

The background image as it would appear on an iPhone 5 or similar 4″ Retina device (640 x 1136).

The same image automatically cropped top and bottom as seen on an iPhone 4 (or similar Retina device with a 3.5" screen).

The same image automatically cropped top and bottom as seen on an iPhone 4 (or similar Retina device with a 3.5″ screen).

The mode setting that makes it work. By default it's set to "Scale to Fill", change it to "Aspect Fill" and it will keep the width full but center and crop the image.

The mode setting that makes it work. By default it’s set to “Scale to Fill”, change it to “Aspect Fill” and it will keep the width full but center and crop the image.

Two images + One setting = Something that gives you easy backgrounds for all small iOS devices

But, if that’s not cutting it for you, there’s another choice. Have a third image ready. iOS has naming conventions for images (you saw some of them above with the @2x) that helps them load the right image for Retina or non-Retina and iPhone/iPod Touch vs iPad. However, they didn’t include a naming convention for the different form factors of 3.5″ vs. 4″.

So an alternative is to load a different image specifically for the Retina 3.5″ and let the non-Retina 3.5″ and Retina 4″ be handled automatically by the image naming conventions. Here’s some sample code that could go in the viewDidLoad to override and load an alternate image:

- (void)viewDidLoad {
  [super viewDidLoad];

  // Do any additional setup after loading the view, typically from a nib.

  // We're relying on automatic loading of background.png and
  // background@2x.png to handle the non-Retina 3.5" devices and the Retina 4"
  // devices.
  //
  // So we're manually detecting Retina 3.5" devices and loading a special
  // image just for those.
  if  ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) &&
    [[UIScreen mainScreen] scale] > 1.0 &&
    [UIScreen mainScreen].bounds.size.height != 568.f) {
      [self.backgroundImageView setImage:[UIImage imageNamed:@"alternateBackground.png"]];
  }
}