Renaissance Nerd

  • Random
  • Archive
  • RSS
  • Ask me anything

Mapping JSON Object Arrays With CoffeeScript

This might be a well-known technique for some of you, but it was new to me when I stumbled onto it last week.

I have a Rails app that’s grabbing some JSON data via AJAX and using the resulting data to display a chart using Highcharts. If you haven’t seen it, Highcharts is a JavaScript library for displaying gorgeous, interactive graphs and charts.

Without getting into the full implementation, when you create a line graph, you have to pass an array of numbers to Highcharts, like this:

series: [{
  name: 'Tokyo',
  data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}

Suppose you get a JSON object back that contains an array of numbers called data. You could just pass it in to Highcharts, right?

series: [{
  name: 'Tokyo',
  data: json['data']
}

Nope. The gotcha is that the values returned in the data array are actually strings, not numbers, so Highcharts will choke if you don’t convert the data from strings to numbers. This is pretty easy. Iterate over the array, typecast the values, store them in a new array, right?

var numerical_data = []
$.each(json['data'], function(k, v) {
  numerical_data[k] = (Number) v;
}

It works, but that’s an ugly approach. Suppose you’re drawing multiple lines, each of which requires its own array of numbers. Doing the conversion via iteration ends up looking really, really gross, and you’ll likely end up duplicating a lot of code.

CoffeeScript’s .map function to the rescue:

series: [
  name: "Cu"
  data: json['data'].map (s) -> (Number) s
,

The map function handles the processing of each item in the array for you and returns a new array with the modified values. If you’re familiar with Ruby, this should look pretty familiar. It’s super-clean, it sticks with the DRY principle, and it’s very easy to read.

    • #coffeescript
    • #JavaScript
    • #json
  • 2 months ago
  • Comments
  • Permalink
  • Share

Using Rake, Pow, and TextExpander for Project Templates

TL;DR: I made a Rakefile to automate the creation of a project template that pulls fresh copies of either Twitter Bootstrap or the HTML5 Boilerplate from GitHub. I serve the template’s HTML with Pow, and I use TextExpander fills to generate boilerplate snippets.


Over the years, I’ve put together a number of project templates, each containing its own set of default HTML, CSS, and JavaScript that I would—invariably—abandon. Each would start off with the best intentions, but I’d fail to routinely update them. They’d grow stale, my workflow would change, and I’d start again.

This cycle repeated itself again recently as I started to move back to Web development in my spare time. Wanting to try out some responsive design techniques, I grabbed a copy of the HTML5 Boilerplate project, tweaked it, added some media queries, and posted it to GitHub. I deleted the repository yesterday because I realized that keeping my template in sync with the HTML5 Boilerplate’s releases would be tedious. Thinking about the problem differently, I turned to Rake, and I’m pretty happy with the results.

Workflow

These days, when I start a project, shortly after some sketching but before I even think about what back-end technology will be powering the site, I focus on building the interface using plain old HTML. My default directory structure looks like this:

I like to use CoffeeScript with Jitter, so I include directories named /coffee and /js. Everything else is pretty straight-forward: /css for CSS, /images for images, and a /resources directory for storing things like PSD files, icon sets, and other project-specific clutter. Finally, the /docs directory is for annotated CoffeeScript documentation that’s generated with Docco.

I create an empty file called application.coffee in the /coffee directory, which ends up compiled to application.js in the /js directory. I also include an empty application.css file in the /css directory. Finally, I toss in an empty index.html file.

If I use a framework like the HTML5 Boilerplate project or Twitter Bootstrap, I download the package and place the project’s various assets into the appropriate directories. The HTML5 Boilerplate’s index.html becomes the default index file when I use that project.

With all of the files in place, I initialize an empty Git repository and start cranking out code. But there’s an easier way.

Rake

This file handles all of the above for me by providing three command-line options.

$> rake newblank

This creates the blank project directory structure and a handful of empty files as outlined in the Workflow section above (complete with a Git repository).

$> rake newhtml5

This clones a copy of the HTML5 Boilerplate project, places its files in the proper directories, and creates a new Git repository.

$> rake newtwitter

This clones a copy of the Twitter Bootstrap project, moves the JavaScript and image assets into the proper directories, compiles the .less files into a single CSS file, runs a quick find-and-replace on the compiled CSS to change references to ../img into ../images because I’m tightly wound and like to name my images directory /images, and creates a new Git repository.

To use it, create a directory for your project and place the contents of this Gist into a file in that directory. Name the file Rakefile. Then, cd into your project’s directory and run one of the above commands.

Advantages

I don’t have to keep my template in sync with changes to projects I use (e.g., the HTML5 Boilerplate project). I don’t have to keep a blank project template full of empty files and directories lying around that will grow stale and require maintenance. I always get the latest HTML5 Boilerplate and Bootstrap code when starting a new project. Everything’s boiled down to one file that’s far easier to maintain and tweak as my needs change. And if a new set of fancy boilerplate comes out, all I have to do is write a new Rake task to add it to my arsenal.

Pow

You can use Pow to serve the flat HTML files you create using any of the templates that are generated by this Rakefile.

Create a directory for your project, and then create a public directory inside your new project’s directory. Place a copy of the Rakefile in the public directory. It should look like this:

cd into the public directory, and run one of the commands to generate the template structure. Then—just like you would with any other Pow-based project—create a link to your project’s directory (not the public directory, but the root project directory) in ~/.pow. For more info on using Pow, see the user’s manual.

Yes, you could just open your plain old HTML files in a browser without having Pow serve them, but using Pow lets you avoid addressing your assets (images, JS, CSS) with relative paths. You won’t have to go through your code and change all the relative paths to full paths once you’re ready to turn your templates into production code.

TextExpander

I love TextExpander, and I use it to fill a gap that’s left by generating blank files with no template code in them. For example, I like my default application.coffee file to include the following header:

#      Project Name v1.0
#      (c) 2012 Company Name
#      http://projecturl.com

# Load the application once the DOM is ready using a `jQuery.ready` shortcut.
$ ->

This block turns into a very pretty header when I run Docco to create my documentation, and it sets the application up to work with jQuery. I created a TextExpander fill to generate this header. The fill, which is triggered when I type coffeehead, prompts me to enter the project name, version, company name, and project URL. For more info on how fills work, see this video by the venerable Merlin Mann.

I have a similar fill that creates the header for my CSS files, which looks like this:

/*
      Project Name v1.0
      (c) 2012 Company Name
      http://projecturl.com
*/


/*  Header
--------------------------------------------- */

This one’s triggered when I type csshead. It’s very similar to the CoffeeScript header. Another fill creates CSS section breaks by prompting me for the name of the section when I type csssec:

/*  Section
--------------------------------------------- */

If you have TextExpander and want to try these snippets for yourself, you can download a copy of them here.

Bonus: Docco

Don’t delete the Rakefile when you’re done generating a new project! It provides a task for creating annotated documentation for your CoffeeScript:

$> rake doc

Run that command, and then check the contents of the /docs directory.

Requirements

I’ll be honest; I lost track of all of the software that’s required to make this work. You’ll need Ruby and Rake and Git to get started. To compile the .less files that come with the Twitter Bootstrap project, you’ll need Node.js and NPM. Once you have NPM installed, you’ll need to install the less package. You can also install CoffeeScript and Docco with NPM; Docco also recommends installing Pygments for syntax highlighting. If I missed any other requirements, please let me know in the comments.

    • #git
    • #coffeescript
    • #javascript
    • #css
    • #html
    • #rake
    • #docco
    • #html5boilerplate
    • #twitterbootstrap
  • 3 months ago
  • 12
  • Comments
  • Permalink
  • Share

Standard CoffeeScript Procedure

Here’s a quick one that I’ve really started to like. I’ve taken to setting up new projects with js and coffee directories in the root of the project. Then, I use Jitter to watch the coffee directory for changes. It automatically recompiles the JavaScript files every time I save my changes.

Jitter takes two arguments: your CoffeeScript directory, and your compiled JavaScript directory, like this:

$> jitter coffee js

So, when I start working, I run that command in the root directory of the project, and Jitter goes to work.

You can make it even simpler by setting up a Bash alias. Add this to your .bashrc or .bash_profile:

alias jjitter='jitter coffee js'

Now, when you start working, just enter jjitter, and you’re off to the races.

    • #bash
    • #coffeescript
    • #JavaScript
  • 4 months ago
  • 17
  • Comments
  • Permalink
  • Share

Node.js and Segmentation Faults

So, this will be (admittedly) short on technical details, but it might help some of you.

I tried to use Homebrew to update my install of Node.js. It worked fine—or so I thought. That is, the install ran flawlessly. But every time I tried to run something with Node, I got this:

Segmentation fault: 11

This was preventing me from updating NPM as well. For the record: Mac OS X Lion (10.7.2) and Node 0.6.5. I fought with it quite a bit, uninstalling and reinstalling Node, but I couldn’t make heads or tails of it.

Finally, I used Homebrew to uninstall Node, and I downloaded the installer package from the Node website. This installs both Node and NPM—hooray! And it fixed the problem—double-hooray!

So, if your install of Node is suddenly segfaulting, grab the installer from the Node site.

Back to writing CoffeeScript.

    • #node
    • #npm
    • #segfault
    • #coffeescript
  • 5 months ago
  • 10
  • Comments
  • Permalink
  • Share

CoffeeScript Tutorial Round-Up

CoffeeScript has been making waves. DHH’s announcement that it will ship with Rails 3.1 (enabled by default!) has generated a glut of tutorials and opinions. Love it or hate it, integration with Rails 3.1 will give it enough traction to ensure that it sticks around for a while. With that in mind, here are a handful of resources to get you started:

  • Rocking Out With CoffeeScript
    A reference-style introduction to the language that covers conditionals, loops, and more.
  • How CoffeeScript makes jQuery more fun than ever
    A quick look at jQuery + CoffeeScript.
  • Rails 3.1: Understanding Sprockets and CoffeeScript
    A great follow-up to Peter Cooper’s How to Play with Rails 3.1, CoffeeScript and All That Jazz Right Now
  • Creating TwitterChimes
    See how to build an entire app with CoffeeScript, Node.js, and a few other new-ish technologies.
  • Using CoffeeScript in Rails and even on Heroku
    A very thorough overview from the venerable Dr Nic that’ll be useful for those of you who want to host on Heroku.
  • CoffeeScript Basics
    TeachMeToCode’s introductory screencast.
  • Meet CoffeeScript
    Peepcode’s new introductory screencast ($12).
  • CoffeeScript: Accelerated JavaScript Development
    Not so much a tutorial as it is a book. $36 for Print + eBook, or $18 for the eBook.

I’ve linked to enough text and video here to fill your entire weekend and then some, so if you haven’t learned CoffeeScript by 5/16, um…try harder?

    • #coffeescript
    • #JavaScript
  • 1 year ago
  • 10
  • Comments
  • Permalink
  • Share
Renaissance Nerd is a collection of links and articles cobbled together (and sometimes written) by Jeff Mueller.

Pages

  • About

Elsewhere

  • @jeffmueller on Twitter
  • jeffmueller on Pinboard
  • jeffmueller on github
Clockpunch: Log time. Track Stats. Stay On Budget

I made an iOS app called Clockpunch. It's for tracking your work. Sales go toward making Renaissance Nerd possible.

  • RSS
  • Random
  • Archive
  • Ask me anything
  • Mobile
Powered by Tumblr

Renaissance Nerd is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. Effector Theme by Carlo Franco.