Lover of all things beautiful

Using GulpJS, Browserify, and Watch for AngularJS Development Feb 5 2014

That’s quite a mouth full, but in a nutshell we just want to develop AngularJS and have Gulp watch our files and recompile them when they change.

var gulp       = require('gulp'),
    _          = require('lodash'),
    fs         = require('fs'),
    nodemon    = require('gulp-nodemon'),
    ini        = require('ini'),
    config     = ini.parse(fs.readFileSync('./.env', 'utf-8')),
    concat     = require('gulp-concat'),
    uglify     = require('gulp-uglify'),
    htmlMin    = require('gulp-minify-html'),
    browserify = require('gulp-browserify'),
    clean      = require('gulp-clean'),
    watch      = require('gulp-watch'),
    ngHtml2Js  = require('gulp-ng-html2js');

gulp.task('default', function(){
  // Update process.env with our .env values
  _.assign(process.env, config);
  nodemon({
    script: 'index.js',
    options: '-e html,js -w lib'
  });
});

gulp.task('clean', function(cb) {
  gulp.src('./build')
    .pipe(clean({
      force: true
    }).on('end', function() {
      cb();
    }));
});

gulp.task('ng', ['clean'], function() {
  buildTemplates("./public/src/**/*.tpl.html", "partials.min.js", "./build/js/");
});

gulp.task('copy', ['clean'], function() {
  copyIndex();
});

gulp.task('bundle', ['clean'], function() {
  buildAppJs('public/src/app.js', './build/js');
});

gulp.task('build', ['ng', 'copy', 'bundle']);

gulp.task('watch', ['build'], function() {
  gulp.src('public/**')
    .pipe(watch(function(files) {
      buildAppJs('public/src/app.js', './build/js');
      buildTemplates("./public/src/**/*.tpl.html", "partials.min.js", "./build/js/");
      copyIndex();
    }));
});

function copyIndex() {
  return gulp.src('public/index.html')
    .pipe(htmlMin({
      empty: true,
      spare: true,
      quotes: true
    }))
    .pipe(gulp.dest('./build/'));
}

function buildAppJs(files, outfile) {
  return gulp.src(files)
    .pipe(browserify())
    .pipe(uglify())
    .pipe(gulp.dest(outfile));
}

function buildTemplates(src, file, dest) {
  return gulp.src(src)
      .pipe(htmlMin({
        empty: true,
        spare: true,
        quotes: true
      }))
      .pipe(ngHtml2Js({
          prefix: "/"
      }))
      .pipe(concat(file))
      .pipe(uglify())
      .pipe(gulp.dest(dest));
}

But what does it all mean ???

Glad you asked. Let me break some of the essential parts down.

We are going to run gulp watch. That will set the task watch in motion. As you see it’s going to run the build command first. This build command will run ng, copy, and bundle, which all of them will wait until the the clean task runs.

  1. clean empties the ./build folder
  2. ng creates builds the AngularJS templates (stores them in the templateCache)
  3. copy this just copies the index.html into ./build
  4. bundle this runs browserify on our AngularJS files and spits it out to ./build
  5. watch will first run all the above to set things up, then it will watch all the files under public/** for changes. When it sees a change it will run the tasks again (except for clean)

I should note that my default task just runs nodemon

Read More

Open current file in Chrome with Vim Dec 5 2013

Most of the time when I’m working on a Markdown document like a README, I want to preview it in Chrome as markdown. Perhaps I’m working on an HTML document and want to preview it in Chrome. It would be a real pain to go to Chrome and then look for the file I’m working on. Luckily Vim makes this really easy.

The Setup

Add this to your .vimrc

" Open up current file in chrome
nmap <silent> <leader>ch :exec 'silent !open -a "Google Chrome" % &'

(Optional) Add a Markdown viewer to Chrome. I use Markdown Preview Plus.

Now in Vim you just need to enter these commands in Normal mode (hint: my <leader> is ,)

,ch[Enter]

That’s all there is to this. It allows you to simply open the current file in Chrome.

References

Read More

iTerm open tab in current working directory Dec 3 2013

I can’t believe I lived so long without looking for a fix to a common issue I have while in iTerm2. Maybe I’m running some GruntJS task that is updating the screen, but I want to do something in the CWD. So I would open another tab ⌘ + t, then cd ... to my cwd.

Instead just tell iTerm you want new tabs to open in the CWD.

  • Open up iTerm2 preferences ⌘ + ,
  • Go to Profiles > General
  • Now click on Edit under Advanced Configuration for Working Directory
  • Now just select when you want it to open in the same directory like so

Now you have an extra 10 seconds a day to do with whatever you want…. live the freedom.

Read More

Instant Messanger Clients Compared Nov 23 2013

Instant messangers are so vital to communcation on the web these days, both in and out of an organization. Let’s take a look at some of the popoular ones out there with their pros and cons. As we compare them, we’ll consider cost, features, portability, and easy of use.

Google Hangouts

Gtalk has been sort of reborn as Hangouts. This web based solution has even just recently had another update that makes it very appealling for group video chats. With hangouts you can contact anyone that has a Google account. Hangouts also supports third party pluggins that help do things like record a video chat session or have your name appear below your video like a news caster does on TV. Screen sharing in Hangouts works great while on a video call.

Pros

  • Ubiquity of the Google network (many people have at least one Google Account)
  • Great video chats right in your browser
  • Free

Cons

  • Poor support for chat rooms and being able to see the history of a chat room.
  • Video chat is browser based, this is a con in my opinion

Campfire

Campfire was developed by 37Signals and integrates well with their products. Campfire was very early on, offering web based chat. You can drag and drop images right into the chat and they are preserved there for reference. I’ll be honest, I’ve only really played with Campfire

Pros

  • Web client

Cons

  • No voice or video, just plain old text chat

HipChat

HipChat and Campfire have a lot in common, but HipChat goes well beyond Campfire. HipChat has a web client as well as native clients for Windows / OS X / iPhone / Android.

Pros

Cons

  • It’s easy to miss undread messages as it does not track these like other instant messaging service.

Skype

Pros

Cons

Read More

Javascript Casting Tricks Oct 22 2013

Here I want to go through some casting tricks that can be used for better data manipulation.

Booleans

Build in Boolean()

The easiest way is to use the builtin Boolean() method.

Boolean('true'); // true
Boolean(1); // true

Boolean('false'); // true !!!!GOTCHA!!!!!
Boolean(0); // false

// Careful
Boolean([]); // true

Double Negative

This will cast anything as either true or false, there are of course a few quirks that may not be obvious.

// FALSE
!!false;
!!null;
!!undefined;
!!0;
!!'';

// TRUE
!!true;
!!'true';
!!1;
!!-1;
!!{};
!!function(){};


// GOTCHA!!! ... TRUE
!!'false';

JSON.parse

This will parse the text 'true' to the boolean true

// TRUE
JSON.parse('true');

// FALSE
JSON.parse('false');

// If using a variable, you'll want a fallback
JSON.parse(undefined || 'true');
JSON.parse('' || 'true');

Numbers

Check for a decimal using modulo

5.5 % 1 != 0; // true
5 % 1 != 0; // false

Reference: http://stackoverflow.com/a/2304062/179335

Strings

Built in tools toString() and String()

var hello = String('hello')
10.0.toString();

Casting an Array as a String

Strings are of course mostly just an array of characters so arrays and strings have a lot in common. You can cast an array to a string simply by joining them with nothing.

var hello = ['h', 'e', 'l', 'l', 'o'];
hello.join('');  // Yields "hello"

Convert from an Array to a String

Strings can be converted to an array easily using split. Here’s how.

var hello = "hello";
hello.split('');  // ['h', 'e', 'l', 'l', 'o'];

Arguments

In Javascript the arguments object in a function is array like, but to convert it to an actually array you can just use a simple trick.

Array.prototype.slice.call(arguments);

Or more simply if Array generics are available (like in node.js).

Array.slice(arguments);

Have one to add? Comment below.

Read More

They shoot email, don't they? Oct 8 2013

So the year is 2013, you send an email off to two coworkers and cc four other people in the company. Think for a minute the utter black hole of despair you just created for six people. Six poor souls now have to read your email and file it away. Let’s take a look at what you’ve set in motion.

Read More

Testing with Karma, Mocha, and ChaiJS Oct 7 2013

Read More

Using Vundle for Vim Plugin Management Sep 30 2013

Vim is the end all, be all of text editors. I don’t care how great Sublime is, or the like. Vim has been around for a long time and for very good reason. You can edit text supremely fast. The plugins just keep getting better.

Vim Plugins

So of course I use plugins. I might try new ones here and there but I have a number of tried and true plugins that I always install. Some that must be noted because they must be noted.

  • NERDTree A file explorer that has more than just that.
  • Fugative A git plugin that will turn you into a git spouting fool
  • Syntastic Code syntax hilighting that will give you goose bumps
  • Tabular Makes lining up vars by their = a breeze

Pathogen">Pathogen

This was a great way to install bundles, you just drop them into the folder and you were rolling. You did need to roll your own gitsubmodule setup if you wanted to propigate your setup to another machine. That works, but man, submodules are a pain in the butt.

Vundle">Vundle

Vundle goes a step further and lets you manage your plugins right in your .vimrc file. After you’ve set them up in your .vimrc file, then just run the command :BundleInstall. Vundle will go through your different plugins, go get them and install them. It Just Works.

Resources

Read More

Good Bye Wordpress, Hello Hexo Sep 20 2013

Hexo">ShaneStillwell.com Moves to Hexo

Posts from here onward will be done using the blog engine Hexo. Read on for more of the journey, or just skip to some cat videos.

A Little Blog History

When www.shanestillwell.com first appeared on the interwebs, it was actually a Wiki. I can’t remember how long that lasted in its form, but maybe around 2006, it bacame a Drupal blog. The intent was to log problems I had on my journey through the technosphere. It was only for me, a sort of log book of issues that I had worked hard to solve and didn’t want to lose that knowledge (or resolve the same problems… raise your hand if you’ve done that). Deja Vu.

Under Drupal the blog thrived and flurished. I was writing posts almost once a week and after a few years had about 100 people a day visiting the blog. I was happy to help others and even thrilled that my blog topped the Google results for certain key phrases.

Then life got busy. It happens. I started blogging less, I started using Drupal much less. Finally, a year or two ago I migrated my blog to WordPress since in my opinion WordPress had won the CMS war with a much more polished admin backend and easier to grok plugins, themes, etc. But by this time in my life I was coding custom Zend Framework apps and didn’t really fancy too much with WordPress. It server a purpose, but I was not excited about it.

Then I learned Vim, and fell out of love with writing in any other editor (especially web based WYSIWYGs and the like). I wanted to code in Vim, and so I converted from using PHPStorm (a great IDE by the way) to Vim and life was peachy. I then learned how easy, fun, and forward thinking Markdown was to write.

So let’s cut this long history short by saying that I’ve found a blog engine that allows me to accomplish the following objectives

  • Use Vim to edit my blog posts
  • Use Markdown as the “markup” of choice
  • Host it off of a static based site (S3, Github, Heroku)
  • Node.js based (ideal, but not required)

Contenders

I’ve been toying with the idea of switching the blog for months. I kept looking for an engine that would fit the bill, but alas I didn’t see one that I liked. I even entertained the idea of writing my own (that’s a common thought in a programmer’s everyday life). Other developers were using Octopress, Jekyll, and some other Ruby based static sties, but they didn’t get me excited. I then stumbled upon Poet, it look interesting, but it was an ExpressJS based site, and I really wanted to have a statically generated site.

Hexo

I’m really happy I found Hexo. One of the worst occurrences I run into is not being able to find what I’m looking for on the web. There might be an awesome piece of software that fits your needs perfectly, but if you can’t find it, well, it might as well not exist.

What I like about Hexo

Node.js

This was not really a requirement, but a HUGE plus in my mind. Node.js is so freaking hot right now, it’s painful just touching the keys while working in a Node.js project.

Markdown

Yeah, this was a requirement, and it does it well. Better yet, it uses the marked module which supports Github Flavored Markdown

Statically Generated HTML

This just means, that you run the command hexo generate and it makes an HTML version of the site for you. No server side language needed. That way you can host off of Github Pages, Heroku, even S3. This makes the page blazingly fast (nothing really beats the performance of static files served by a web server, except an Single Page App). Also, static pages are more suitable for permalink / long lasting posts (No Database Needed).

Built In Server

You can run hexo server and get a local web server to view your site live, so you can preview what your post will look like. I’ve saved and previewed this article at least 10 times so far to this point.

Wordpress Migration Plugin

For the record, it was a lot more painful going from Drupal -> Wordpress, than from Wordpress -> Hexo. Hexo provides a plugin to help you migrate your blogs. For Wordpress, it’s as simple as the following.

  1. Go into the Wordpress admin. Select Tools -> Export.
    1. This will export your data to an XML file locally to your computer
  2. Go to the source directory of your hexo blog and run the command hexo migrate wordpress SOURCE, where SOURCE is the xml file you downloaded from Wordpress.
  3. I had a few problem lines in my xml. After I manually deleted them, the migration worked flawlessly.

Conclusion

I’m excited to start blogging again, hence the long post. Look for more blog posts from me in the coming future now that I can write them in Vim, Markedown and push with or without an internet conneciton. (For the record, I’m 38K feet in the air right now with no interweb connection).

Update

The new blogging platform Ghost looks very intersting, but I’m married to Vim.

Read More

The MEAN Stack Jun 12 2013

Maybe you’re familiar with the LAMP stack? Linux, Apache, MySql, PHP. That’s been a pretty common way to serve websites for many years (circa 1998?). But things have changed, technologies have changed, and it’s not 1998 anymore. IE6 is dead, nested tables are dead, and the LAMP stack is the Old and Busted.

The New Hotness is the MEAN stack, MongoDB, ExpressJS, AngularJS, and NodeJS. This new stack of technologies is what many new web apps are using these days.

MongoDB

Ever since I started using MongoDB over a year ago I have not even considered using MySQL for a web project. I suppose it has its place, but the ease of storing your data as it really is instead of weird joins and relations makes a whole lot more sense to me. The beauty of MongoDB and NoSQL in general is the schema is regulated by the app. No more crazy schema migration scripts to keep your MySQL schema in tact.

I should also mention the other M you’ll want to use, when using NodeJS and MongoDB, and that’s MongooseJS. Mongoose makes working with MongoDB a breeze and adds so many convenient operations for querying, saving, updating, and deleting records.

ExpressJS">ExpressJS

I had to try to explain to a coworker the other day how the MEAN stack equates to the LAMP stack and I was at amiss to communicate it. In a nutshell, ExpressJS makes creating a REST API dead simple. Express handles requests, routes, and responses. Throw in middleware and you have a supremely easy way to whip out a REST based API in no time.

Express lets you break the functions for different operations into small reusable chunks of code. Then combine them as you need them for different routes. For example, maybe some of your website is protected by authentication, and other parts are not. The auth protected routes can just call an auth() function and BAM!!! User authentication is now required for that particular route. Just to be clear a route is defined as an HTTP verb (GET, POST) and a URL (/user/profile).

AngularJS

New kid on the block is AngularJS. Developed for a few years by Misko, Igor, and Vojtia at Google, it’s now just come into its own. AngularJS is client side only and doesn’t care what you’re running on the backend. Rumor has it, the .Net crowd really loves AngularJS too, go figure.

AngularJS is a Single Page App (SPA). Once loaded into the browser it “fakes” page loads, by just loading different templates and changing the URL. This makes page loads extremely fast as all you’re waiting for is the data for that page. The CSS, JS, and most of the HTML is already there in the browser. AngularJS updates the page for you, it detects changes in your data and will update the page on the fly to reflect this change. For example, if you have a form to update some inforamtion, AngularJS, will update it live on the page as the form is being filled out. Truly awesome.

NodeJS">NodeJS

Let’s not forget the workhorse of this whole stack, NodeJS. Node is fast, efficient, and can do anything. Node’s popularity lately has skyrocketed and for good reason, it’s fast, modular, testable, and flexible. Node coupled with Express makes for a very powerful web server (hint: most people put Node behind Nginx)

Read More