<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bill Broughton on Medium]]></title>
        <description><![CDATA[Stories by Bill Broughton on Medium]]></description>
        <link>https://medium.com/@bill_broughton?source=rss-816613247cb6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hMEUXRNG9x2bpF0-RkKukQ.png</url>
            <title>Stories by Bill Broughton on Medium</title>
            <link>https://medium.com/@bill_broughton?source=rss-816613247cb6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:14:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bill_broughton/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Quick Intro to Dockerfile]]></title>
            <link>https://medium.com/@bill_broughton/quick-intro-to-dockerfile-74459115b10a?source=rss-816613247cb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/74459115b10a</guid>
            <category><![CDATA[meteor]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Bill Broughton]]></dc:creator>
            <pubDate>Sat, 30 Jan 2016 11:46:28 GMT</pubDate>
            <atom:updated>2016-03-03T01:06:12.770Z</atom:updated>
            <content:encoded><![CDATA[<p>For a while I was using VirtualBox/Vagrant for development projects. More recently I’ve moved to using Docker. I use Linux (lubuntu) on my dev computer anyways, so it was an easy transition and the resource consumption is significantly lower. I haven’t tried Docker in a Windows or Mac environment, so I can’t speak to the performance or resource consumption on those platforms.</p><p>Docker is actually pretty straightforward to use. The one thing that I got hung up on was the Dockerfile. It’s not very complex, but you do need to know what you’re doing.</p><p>I’m working on a Meteor project right now, so I wanted to create a new Dockerfile to make future projects quick to spin up. I’ll walk through each part of the Dockerfile and explain what’s going on. Bolded lines are the commands in the Dockerfile and the following text explains what the command is doing.</p><p>There is a <a href="https://github.com/techspringllc/docker-meteor">Github repo</a> and a <a href="https://hub.docker.com/r/techspring/meteor-dev/">Docker Hub</a> page for this Docker image.</p><p><strong>FROM ubuntu</strong></p><p>For this project I want to use the latest ubuntu base image. If I wanted to use a specific version, like 14.04, I would use the command “FROM ubuntu:14.04”. You can use any image from <a href="https://hub.docker.com/explore/">Docker Hub</a> as your base.</p><p><strong>MAINTAINER Bill Broughton &lt;email redacted&gt;</strong></p><p>The MAINTAINER command isn’t strictly necessary, but if you are going to publish your image to Docker Hub it should be in your file. This just identifies who is maintaining the image.</p><p><strong>RUN &lt;shell command&gt;</strong></p><p>RUN allows you to execute shell commands during the image creation. This is most frequently used for ‘apt-get install’ commands, but it can be used for other shell commands also.</p><p>My Dockerfile has three RUN commands.</p><pre># Fix MongoDB locale issue<br>RUN locale-gen en_US.UTF-8</pre><pre># Update apt and install git, curl, python, and latest node<br>RUN apt-get update &amp;&amp; apt-get install -y \<br> git \<br> curl \<br> python \<br> &amp;&amp; (curl <a href="https://deb.nodesource.com/setup">https://deb.nodesource.com/setup</a> | sh) \<br> &amp;&amp; apt-get install -y nodejs \<br> &amp;&amp; apt-get clean \<br> &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><pre># Install Meteor<br>RUN curl <a href="https://install.meteor.com/">https://install.meteor.com/</a> |sh</pre><p>The first RUN command sets the locale in Ubuntu. This is necessary because MongoDB won’t work without having a locale set. The next RUN command installs git, curl, python, and nodejs. It then clears the apt-cache and deletes the contents of the apt lists directory. These steps are part of Docker’s best practices and helps to keep image size down. Finally, the last RUN command installs <a href="https://www.meteor.com/install">Meteor</a> per the directions on their site.</p><p><strong>EXPOSE 3000</strong></p><p>The default port that Meteor runs on in development is 3000, this command lets the container know to watch for connections to port 3000.</p><p><strong>VOLUME [“/app”]</strong></p><p>VOLUME exposes directories to the container. Generally, you will want to expose any directories that are intended to be user-serviceable.</p><p><strong>WORKDIR /app</strong></p><p>This sets the working directory to the volume that was exposed in the previous command. When you enter the interactive shell of the container, you will be located in /app.</p><p><strong>CMD [“/bin/bash”]</strong></p><p>The CMD command can be used to execute shell scripts in the container. In a production application, this would be used to start the application with the container. In a development environment, users of the image probably want to go to the interactive shell. When the container is started with the ‘-it’ flag, they will be taken to an interactive shell.</p><h4>How to use it</h4><p>To build an image from the Dockerfile, run the following command from the directory containing the Dockerfile:</p><pre>docker build -t &lt;image-name&gt; .</pre><p>The ‘-t’ flag allows you to give the image an easy to remember name rather than a hash. The period at the end references the current working directory. You can also build an image not in your current working directory by specifying a full path instead.</p><p>To start the image in a new container, link the /app directory in the container to your current working directory on your host, and start an interactive shell, use this:</p><pre>docker run -it --name &lt;container-name&gt; -v &quot;$(pwd)&quot;:/app &lt;image-name&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74459115b10a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing with authenticated routes in Express]]></title>
            <link>https://medium.com/@bill_broughton/testing-with-authenticated-routes-in-express-6fa9c4c335ca?source=rss-816613247cb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fa9c4c335ca</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Bill Broughton]]></dc:creator>
            <pubDate>Mon, 05 Oct 2015 01:59:53 GMT</pubDate>
            <atom:updated>2015-10-05T01:59:53.015Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently had a problem. I’m working on an Express API project and writing tests with Mocha/Should/Supertest. Everything was going great and all of my tests were passing and then I added authentication (using Passport) to my routes.</p><p>As expected, my tests were now failing. Not as expected was the difficulty in getting the tests back to passing. I (eventually) found a <a href="https://gist.github.com/joaoneto/5152248">Github Gist</a> that got me most of the way there, but I couldn’t get it to work. As it turns out, it was just a small tweak that allowed me to get back to passing tests.</p><p>With great appreciation to <a href="https://gist.github.com/joaoneto">joaoneto</a>, here’s how to get passing tests with authenticated routes in Express.</p><p>To set the stage I’ll present an arbitrary test that I will base the remainder of the code on.</p><pre>&#39;use strict&#39;;<br>var should = require(&#39;should&#39;);<br>var app = require(&#39;../../app&#39;);<br>var request = require(&#39;supertest&#39;)(app);</pre><pre>describe(&#39;useless api endpoint&#39;, function() {<br>  it(&#39;posts an object&#39;, function(done) {<br>    request.post(&#39;/api/useless&#39;)<br>      .send({ property: value })<br>      .expect(201)<br>      .end(function(err, res) {<br>        should(err).equal(null);<br>        done()<br>      });<br>  });<br>});</pre><p>My first attempt, before finding the Gist, was to simply use supertest to post to the login endpoint and go about my business assuming the session data would carry.</p><pre>before(function(done) {<br>  request.post(‘/auth/local’)<br>    .send({<br>      email: ‘<a href="/service/mailto:nikola@tesla.com">t</a>est@user.com’,<br>      password: ‘password’<br>    })<br>    .end(function(err, res) {<br>      if (err) throw err;<br>      done();<br>    });<br>});</pre><p>Unfortunately, the cookie data didn’t persist and the call to the authenticated route returned an error. Using the Gist, I added a `token` variable that would carry the token returned from logging in. But adding the token to req.cookies wasn’t getting the desired result. The Gist is from three years ago, so I’m assuming my struggle was the result of a change to supertest’s codebase. I eventually figured out that I could pass the token with supertest’s query method.</p><pre>&#39;use strict&#39;;<br>var should = require(&#39;should&#39;);<br>var app = require(&#39;../../app&#39;);<br>var request = require(&#39;supertest&#39;)(app);</pre><pre>describe(&#39;useless api endpoint&#39;, function() {<br>  var token;<br>  before(function(done) {<br>    request.post(‘/auth/local’)<br>      .send({<br>        email: ‘<a href="/service/mailto:nikola@tesla.com">t</a>est@user.com’,<br>        password: ‘password’<br>      })<br>      .end(function(err, res) {<br>        if (err) throw err;<br>        token = { access_token: res.body.token }<br>        done();<br>      });<br>  });<br>  <br>  it(&#39;posts an object&#39;, function(done) {<br>    request.post(&#39;/api/useless&#39;)<br>      .send({ property: value })<br>      .query(token)<br>      .expect(201)<br>      .end(function(err, res) {<br>        should(err).equal(null);<br>        done()<br>      });<br>  });<br>});</pre><p>FWIW, I tried a lot of other solutions including supertest-session and some really hack-y stuff before I landed on this. Hopefully I can save at least one other person from going down the rabbit hole for 4–5 hours like I did.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fa9c4c335ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up mockgoose with angular-fullstack]]></title>
            <link>https://medium.com/@bill_broughton/setting-up-mockgoose-with-angular-fullstack-40e1c6982d69?source=rss-816613247cb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/40e1c6982d69</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[mockgoose]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Bill Broughton]]></dc:creator>
            <pubDate>Thu, 01 Oct 2015 20:16:24 GMT</pubDate>
            <atom:updated>2015-10-01T20:16:24.078Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m using the Yeoman angular-fullstack generator for a MEAN project that I’m working on and I wanted to be able to mock the database connection for quicker testing. I found <a href="https://github.com/mccormicka/Mockgoose">mockgoose</a>, but I wasn’t clear on how to implement it in this environment. Without further ado, here are the steps.</p><p>First, install mockgoose with npm:</p><pre>npm install mockgoose --save-dev</pre><p>Open the file {project-base}/server/app.js and find the block starting with // Connect to database:</p><pre>mongoose.connect(config.mongo.uri, config.mongo.options);<br>mongoose.connection.on(‘error’, function(err) {<br>  console.error(‘MongoDB connection error: ‘ + err);<br>  process.exit(-1);<br>  }<br>);</pre><p>Edit this block to the following:</p><pre>if (process.env.NODE_ENV == ‘test’) {<br>  var mockgoose = require(‘mockgoose’)(mongoose);<br>  mongoose.connect(config.mongo.uri);<br>} else {<br>  mongoose.connect(config.mongo.uri, config.mongo.options);<br>  mongoose.connection.on(‘error’, function(err) {<br>    console.error(‘MongoDB connection error: ‘ + err);<br>    process.exit(-1);<br>    }<br>  );<br>}</pre><p>That’s it! I’m working on a micro cloud instance, so changing to mockgoose took my test run time from 88 seconds to 2.3 seconds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40e1c6982d69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Provisioning a Development Box with Vagrant]]></title>
            <link>https://medium.com/@bill_broughton/provisioning-a-development-box-with-vagrant-51be2ae95c11?source=rss-816613247cb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/51be2ae95c11</guid>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[vagrant]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Bill Broughton]]></dc:creator>
            <pubDate>Fri, 05 Jun 2015 21:30:50 GMT</pubDate>
            <atom:updated>2015-06-05T21:37:54.895Z</atom:updated>
            <content:encoded><![CDATA[<p>I try to automate just about every repetitive thing that I do on a computer. Seriously, it’s bordering on being a disorder. I just hate spending hours doing the same thing over and over again that a computer can do in minutes while I go make a cup of coffee.</p><p>Vagrant is perfect for me then, because it allows me to set up a consistent, repeatable development environment once and then boot into a clean version whenever I want within minutes. It’s a little more work up front, but it really pays off in the long run.</p><h3>What are we doing here?</h3><p>I’m going to walk through the process of creating the necessary files to automatically provision fresh development environments using Vagrant. For this example, I’m going to set up a LAMP stack along with a bunch of development tooling. It will be called, rather unimaginatively, vagrant-lamp-dev. You can find all of the files in my <a href="https://github.com/wlbrough/vagrant-lamp-dev">github repo</a>.</p><h3>Prerequisites</h3><p>In order to follow along, you’ll need a few things. If you don’t already have this stuff installed on your system, follow the instructions at the provided links to get it installed.</p><ul><li>Virtualbox (<a href="https://www.virtualbox.org/wiki/Downloads">download</a>)</li><li>Vagrant (<a href="http://www.vagrantup.com/downloads">download</a>)</li><li>Vagrant-HostsUpdater (<a href="https://github.com/cogitatio/vagrant-hostsupdater">github</a>) (**optional**)</li></ul><h3>Vagrantfile</h3><p>The Vagrantfile is where you set up the basic aspects of the virtual machine. This is where you define things such as what base box to use, the system resources for the VM, host name, etc.</p><p>The basic structure of the Vagrantfile will (almost) always be</p><pre>Vagrant.configure(“2”) do |config|<br>  # Config goes here<br>end</pre><p>The only exception to that is if you are trying to do some configuration that needs to be compatible with early versions of Vagrant in which case you would need a “1” instead of the “2”. This is just a block that contains your configuration settings.</p><p>The first thing that I will do is specify the base box that my environment will be provisioned on top of. In this case, I will specify Ubuntu 14.04 Server 64-bit. You can find a list of available boxes on the <a href="https://atlas.hashicorp.com/boxes/search">Hashi Corp website</a>.</p><pre>config.vm.box = &quot;ubuntu/trusty64&quot;</pre><p>Next we’ll set up the hostname and networking for the VM.</p><pre>config.vm.hostname = &quot;vagrant-lamp-dev&quot;<br>config.vm.network :private_network, ip: &quot;192.168.40.7&quot;<br>config.hostsupdater.aliases = %w(lamp.dev)<br>config.hostsupdater.remove_on_suspend = true</pre><p>The first line in this block just sets the hostname to “vagrant-lamp-dev”. The next line configures a private network IP address. Why did I choose “192.168.40.7”? Because there’s nothing else on my network with that IP address. Your mileage may vary. It is possible to configure a public network IP address that would allow access from other devices on your network, but I’ll assume that’s not a desired behavior here.</p><p>If you have Vagrant-HostsUpdater installed, the next two lines configure an entry to your local machine’s hosts file so that when you enter vagrant.wp into a browser, you will be directed to the configured IP address. The remove_on_suspend setting removes the hosts file entry each time you exit the VM.</p><p>Next, we’ll configure some settings for the VM.</p><pre>config.vm.provider :virtualbox do |v|<br>  v.customize [&quot;modifyvm&quot;, :id, &quot;--memory&quot;, 1024]<br>  v.customize [&quot;modifyvm&quot;, :id, &quot;--natdnshostresolver1&quot;, &quot;on&quot;]<br>  v.customize [&quot;modifyvm&quot;, :id, &quot;--natdnsproxy1&quot;, &quot;on&quot;]<br>end</pre><p>The first line here just sets up the block for the Virtualbox specific config settings. The first line inside the block specifies a memory allocation of 1Gb. The next two lines in the config are used to resolve slow network issues and are pretty much boilerplate in Vagrantfiles.</p><p>Finally, lets specify where to look for the provisioning file that will do the rest of the work. I will be using the shell provisioning method, but you can get more advanced and use Puppet or Chef also. For this exercise I will add a file called bootstrap.sh to the same directory as the Vagrantfile.</p><pre>config.vm.provision :shell, :path =&gt; &quot;bootstrap.sh&quot;</pre><p>That’s it! Now you have a fully functioning Vagrantfile. Next up is the interesting stuff.</p><h3>bootstrap.sh</h3><p>To borrow an expression from the MTV masterpiece “Cribs”, this is where the magic happens. This is just a shell script that gets run after the VM is set up. I’m going to keep it relatively simple here, but it would be wise to use conditionals throughout to skip redundant operations if you re-provision at some point after you first build the VM.</p><p>The first thing I want to do is install a bunch of packages to provide the functionality that I need.</p><pre>apt_package_list = (<br> # lots of packages — see <a href="https://github.com/wlbrough/vagrant-lamp-dev">github</a><br>)<br>apt-get update --assume-yes<br>apt-get install --assume-yes ${apt_package_list[@]}<br>apt-get clean</pre><p>First we build an array of all of the packages that we want to install. It’s a pretty exensive list, so I’ve left it out from this article. Next we update the package lists, install all of the packages in the array, then clean up the apt cache.</p><p>Make sure npm is up to date and install the npm update checker.</p><pre>npm install -g npm<br>npm install -g npm-check-updates</pre><p>I use Bower, so that’s next up on the list.</p><pre>npm install -g bower</pre><p>I’m a recent Gulp convert, so Gulp and all of the typical plugins I use are coming up next.</p><pre>npm install -g gulp<br>npm install -g gulp-util<br>npm install -g gulp-sass<br>npm install -g gulp-autoprefixer<br>npm install -g gulp-coffee<br>...(continues)</pre><p>That’s it! Now everything is in place to launch the VM.</p><h3>Launch</h3><p>Now `cd` into the directory with the Vagrantfile and run</p><pre>vagrant up</pre><p>This would be a good time to go get a coffee and a snack or deal with your email backlog. There is a lot of downloading and installing to be done, so it will take a while.</p><p>When everything is done, you will be able to navigate to `http://lamp.dev/` and see the Apache default page in your browser. You can ssh into the VM with the command</p><pre>vagrant ssh</pre><h3>Fin</h3><p>There’s a lot more to Vagrant than what was covered here. I would recommend looking through the docs on the <a href="http://www.vagrantup.com/">Vagrant website</a> and playing around with other features. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51be2ae95c11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TodoMVC in ember-cli]]></title>
            <link>https://medium.com/@bill_broughton/todomvc-in-ember-cli-3bfe2d3c95e4?source=rss-816613247cb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bfe2d3c95e4</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ember]]></category>
            <dc:creator><![CDATA[Bill Broughton]]></dc:creator>
            <pubDate>Thu, 23 Apr 2015 13:48:37 GMT</pubDate>
            <atom:updated>2015-04-23T13:48:37.741Z</atom:updated>
            <content:encoded><![CDATA[<p>A few weeks ago, I decided to jump into Ember.js and try my hand at building a fully client-side app. The tutorial on Ember’s site that walks through an implementation of TodoMVC is well written and has good depth, but it is somewhat outdated. It includes some depricated elements and does not use ember-cli, which is the recommended implementation as of the current version.</p><p>As a way to teach myself the new framework and to provide others a good basis for starting out, I decided to rework the existing tutorial to bring it up to date.</p><p>This tutorial borrows heavily from the original work done by <a href="https://github.com/trek">Trek Glowacki</a>. When I have a chance, I’ll do a pull of the Ember documentation and update it with the content from this article.</p><p>Installation directions can be found on the <a href="http://guides.emberjs.com/v1.11.0/ember-cli/">Ember.js website</a>.</p><p>The original tutorial can be found on the <a href="http://guides.emberjs.com/v1.10.0/getting-started/planning-the-application/">Ember.js website</a>.</p><p>The source for this tutorial is available on <a href="https://github.com/wlbrough/ember-cli-todomvc">github</a>.</p><h4>Create the application skeleton</h4><p>Navigate to the folder that you want to create your project in and execute the following.</p><pre>ember new ember-cli-todomvc<br>cd ember-cli-todomvc<br>ember serve</pre><p>This will scaffold out the application structure and give you a starting point to build on. All bash commands going forward are in the application directory. When files are referenced throughout this tutorial, they will be provided with the path assuming that the application directory is the base.</p><p><strong>ember serve</strong> instantates a server that you can access at <strong>localhost:4200</strong> and will watch for changes in the application directory.</p><h4>Install TodoMVC base</h4><p>The fine folks at <a href="http://www.todomvc.com/">TodoMVC</a> provide the CSS for the application, so we don’t have to build it from scratch.</p><pre>ember install:bower todomvc-app-css<br>ember install:bower todomvc-common</pre><p>All dependencies are added to <strong>Brocfile.js</strong> before <strong>module.exports = app.toTree();</strong>. You can only import assets from the bower_components and vendor directories.</p><pre>app.import(&#39;bower_components/todomvc-common/base.css&#39;);<br>app.import(&#39;bower_components/todomvc-app-css/index.css&#39;);</pre><h4>Create a static mockup of the app</h4><p>Before adding any code, create a static mockup of the app to <strong>app/templates/application.hbs</strong>. There is no need to add links to the CSS files, as that will be handled by Ember’s built-in dependency management.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;title&gt;Ember.js • TodoMVC&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;section class=&quot;todoapp&quot;&gt;<br>      &lt;header class=&quot;header&quot;&gt;<br>        &lt;h1&gt;todos&lt;/h1&gt;<br>        &lt;input type=&quot;text&quot; class=&quot;new-todo&quot; placeholder=&quot;What needs to be done?&quot; /&gt;<br>      &lt;/header&gt;</pre><pre>      &lt;section class=&quot;main&quot;&gt;<br>        &lt;ul class=&quot;todo-list&quot;&gt;<br>          &lt;li class=&quot;completed&quot;&gt;<br>            &lt;input type=&quot;checkbox&quot; class=&quot;toggle&quot;&gt;<br>            &lt;label&gt;Learn Ember.js&lt;/label&gt;&lt;button class=&quot;destroy&quot;&gt;&lt;/button&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;input type=&quot;checkbox&quot; class=&quot;toggle&quot;&gt;<br>            &lt;label&gt;...&lt;/label&gt;&lt;button class=&quot;destroy&quot;&gt;&lt;/button&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;input type=&quot;checkbox&quot; class=&quot;toggle&quot;&gt;<br>            &lt;label&gt;Profit!&lt;/label&gt;&lt;button class=&quot;destroy&quot;&gt;&lt;/button&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;</pre><pre>        &lt;input type=&quot;checkbox&quot; class=&quot;toggle-all&quot;&gt;<br>      &lt;/section&gt;</pre><pre>      &lt;footer class=&quot;footer&quot;&gt;<br>        &lt;span class=&quot;todo-count&quot;&gt;<br>          &lt;strong&gt;2&lt;/strong&gt; todos left<br>        &lt;/span&gt;<br>        &lt;ul class=&quot;filters&quot;&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;all&quot; class=&quot;selected&quot;&gt;All&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;active&quot;&gt;Active&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;completed&quot;&gt;Completed&lt;/a&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;</pre><pre>        &lt;button class=&quot;clear-completed&quot;&gt;<br>          Clear completed (1)<br>        &lt;/button&gt;<br>      &lt;/footer&gt;<br>    &lt;/section&gt;</pre><pre>    &lt;footer class=&quot;info&quot;&gt;<br>      &lt;p&gt;Double-click to edit a todo&lt;/p&gt;<br>    &lt;/footer&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>This will be modified throughout the tutorial as features are implemented.</p><h4>Adding first route and template</h4><p>ember-cli utilizes generators similar to Rails. Generators are called using <strong>ember generate</strong> or <strong>ember g</strong> for short. This tutorial will use the short form.</p><p>The <strong>route</strong> generator has two options:</p><ul><li><strong>type</strong> can be either <strong>route</strong> or <strong>resource</strong></li><li><strong>path</strong> which specifies a path other than what can be directly inferred using the route name</li></ul><p>A <strong>resource</strong> does not change the URI, whereas a <strong>route</strong> does.</p><p>Use the route generator to create a resource at the URI root.</p><pre>ember g route todos --type=resource --path &#39;/&#39;</pre><p>The generator will create three files:</p><ul><li>app/routes/todos.js</li><li>app/templates/todos.hbs</li><li>tests/unit/routes/todos-test.js</li></ul><p>The generator also modifies <strong>app/router.js</strong> to reflect the new route/resource.</p><p>Copy all HTML between <strong>&lt;body&gt;</strong> and <strong>&lt;/body&gt;</strong> to <strong>app/templates/todos.hbs</strong>. Replace copied HTML in <strong>app/templates/application.hbs</strong> with <strong>{{outlet}}</strong>.</p><pre>//...<br>&lt;body&gt;<br>    {{outlet}}<br>&lt;/body&gt;<br>//...</pre><h4>Modeling data</h4><p>Use the model generator to create a new <strong>todo</strong> model.</p><pre>ember generate model todo</pre><p>This will create two new files:</p><ul><li>/app/models/todo.js</li><li>tests/unit/models/todo-test.js</li></ul><p>Modify <strong>app/models/todo.js</strong> to the following</p><pre>export default DS.Model.extend({<br>    title: DS.attr(&#39;string&#39;),<br>    isCompleted: DS.attr(&#39;boolean&#39;)<br>});</pre><h4>Create mock for fixture data</h4><p>Previous versions of Ember used fixtures for mock data. While fixtures are still available, it is now recommended that you use http-mock which creates a simple Express.js server that will run when you use <strong>ember serve</strong>.</p><p>http-mock is very simple to setup and use. The generator does most of the work for you.</p><pre>ember g http-mock todos</pre><p>Add the mock data in JSON format between the <strong>[]</strong> in <strong>server/mocks/todos.js</strong>.</p><pre>{<br>    id: 1,<br>    title: &#39;Learn Ember.js&#39;,<br>    isCompleted: true<br>},<br>{<br>    id: 2,<br>    title: &#39;...&#39;,<br>    isCompleted: false<br>},<br>{<br>    id: 3,<br>    title: &#39;Profit!&#39;,<br>    isCompleted: false<br>}</pre><p>Use the generator to create a new adapter.</p><pre>ember g adapter application</pre><p>The adapter will be created at <strong>app/adapters/application.js</strong>. Open this file and modify it to read as follows.</p><pre>import DS from &#39;ember-data&#39;;</pre><pre>export default DS.RESTAdapter.extend({<br>    namespace: &#39;api&#39;<br>});</pre><p>By default, http-mock serves the data from /api/todos, which necessitates the namespace.</p><h4>Displaying model data</h4><p>Now that data is available to the application, the code will be modified to display the dynamic data rather than the static mockup.</p><p>To serve the data to the template, we first need to modify <strong>app/routes/todos.js</strong> so it knows what data to pull. Add the following inside the <strong>extend</strong> block.</p><pre>model: function() {<br>    return this.store.find(&#39;todo&#39;);<br>}</pre><p>Now <strong>app/templates/todos.hbs</strong> can be modified to replace the static <strong>&lt;li&gt;</strong> elements with the Handlebars <strong>{{each}}</strong> helper.</p><pre>//...<br>&lt;ul class=&quot;todo-list&quot;&gt;<br>    {{#each todo in model}}<br>        &lt;li&gt;<br>            &lt;input type=&quot;checkbox&quot; class=&quot;toggle&quot;&gt;<br>            &lt;label&gt;{{todo.title}}&lt;/label&gt;&lt;button class=&quot;destroy&quot;&gt;&lt;/button&gt;<br>        &lt;/li&gt;<br>    {{/each}}<br>&lt;/ul&gt;<br>//...</pre><p>Because no custom behavior is required from the controller at this point, we can rely on the default controller provided by the framework.</p><h4>Displaying a model’s complete state</h4><p>TodoMVC uses the <strong>completed</strong> class to apply a strikethrough to completed todos. Modify the <strong>&lt;li&gt;</strong> element in <strong>app/templates/todos.hbs</strong> to apply the class when a todo’s <strong>isCompleted</strong> property is true.</p><pre>&lt;li {{bind-attr class=&quot;todo.isCompleted:completed&quot;}}&gt;</pre><h4>Creating a new model instance</h4><p>Now that we can display the data, we can make some changes so we can add items to the todo list.</p><p>First, replace the <strong>input</strong> element in <strong>apps/templates/todos.hbs</strong> with an <strong>{{input}}</strong> helper.</p><pre>&lt;h1&gt;todos&lt;/h1&gt;<br>{{input type=&quot;text&quot; class=&quot;new-todo&quot; placeholder=&quot;What needs to be done?&quot; value=newTitle action=&quot;createTodo&quot;}}<br>//...</pre><p>The helper binds the <strong>newTitle</strong> property of the controller to the <strong>value</strong> attribute of the input.</p><p>Next, use the generator to create a <strong>todos</strong> controller to implement custom logic.</p><pre>ember g controller todos</pre><p>In the newly generated <strong>app/controllers/todos.js</strong> change <strong>Ember.Controller.extend</strong> to <strong>Ember.ArrayController.extend</strong> so it will handle the array data that we are passing to it.</p><p>Add the following to the extend block</p><pre>actions: {<br>    createTodo: function() {<br>        var title = this.get(&#39;newTitle&#39;);<br>        if (!title.trim()) { return; }</pre><pre>        var todo = this.store.createRecord(&#39;todo&#39;, {<br>            title: title,<br>            isCompleted: false<br>        });</pre><pre>        this.set(&#39;newTitle&#39;, &#39;&#39;);</pre><pre>        todo.save();<br>    }<br>}</pre><p><strong>createTodo</strong> gets the <strong>newTitle</strong> property and creates a new todo record using the input as the title and setting <strong>isCompleted</strong> to false. It then clears the input and saves the record to the store.</p><h4>Marking a model as complete or incomplete</h4><p>Next up, we will add the ability to mark a todo as complete or incomplete and persist the update.</p><p>First, update a<strong>pp/templates/todos.hbs</strong> by adding an <strong>itemController</strong> to the <strong>{{each}}</strong> helper. Also, convert the static <strong>&lt;input&gt;</strong> element to an <strong>{{input}}</strong> helper.</p><pre>{{#each todo in model itemController=&quot;todo&quot;}}<br>    &lt;li {{bind-attr class=&quot;todo.model.isCompleted:completed&quot;}}&gt;<br>        {{input type=&quot;checkbox&quot; checked=todo.model.isCompleted class=&quot;toggle&quot;}}<br>        &lt;label &gt;{{todo.model.title}}&lt;/label&gt;&lt;button class=&quot;destroy&quot;&gt;&lt;/button&gt;<br>    &lt;/li&gt;<br>{{/each}}</pre><p>Notice that <strong>todo.isCompleted</strong> has been changed to <strong>todo.model.isCompleted</strong>. This is a result of the way the new todo controller is structured. Ember recently depricated the <strong>ObjectController</strong> class in favor of the easier to remember <strong>Controller</strong> class, which is part of the reason for this change.</p><p>A new controller needs to be created for working with the individual todos. Use the generator to create the controller.</p><pre>ember g controller todo</pre><p>In the <strong>extend</strong> block of <strong>app/controllers/todo.js</strong> add this code.</p><pre>isCompleted: function(key, value) {<br>    var model = this.get(&#39;model&#39;);</pre><pre>    if (value === undefined) {<br>        return model.get(&#39;isCompleted&#39;);<br>    } else {<br>        model.set(&#39;isCompleted&#39;, value);<br>        model.save();<br>        return value;<br>    }<br>}.property(&#39;model.isCompleted&#39;)</pre><p>The <strong>isCompleted</strong> property of the controller is a computed property whose value is dependent on the value of the model instance’s <strong>isCompleted</strong> property.</p><p>When called with a value, because the user clicked the checkbox, the controller will toggle the model instance’s <strong>isCompleted</strong> property and persist the change. When called without a value, such as on the page load, it will simply return the value of the model instance’s <strong>isCompleted</strong> property.</p><h4>Displaying the number of incomplete todos</h4><p>Update <strong>app/templates/todos.hbs</strong> as shown below.</p><pre>&lt;span class=&quot;todo-count&quot;&gt;<br>    &lt;strong&gt;{{remaining}}&lt;/strong&gt; {{inflection}} left<br>&lt;/span&gt;</pre><p>Implement the <strong>remaining</strong> and <strong>inflection</strong> properties in <strong>app/controllers/todos.js</strong>.</p><pre>actions: {<br>    // ...<br>},<br>remaining: function() {<br>    return this.filterBy(&#39;isCompleted&#39;, false).get(&#39;length&#39;);<br>}.property(&#39;@each.isCompleted&#39;),<br>inflection: function() {<br>    var remaining = this.get(&#39;remaining&#39;);<br>    return remaining === 1 ? &#39;item&#39; : &#39;items&#39;;<br>}.property(&#39;remaining&#39;)</pre><p>The <strong>remaining</strong> property returns the number of todos whose <strong>isCompleted</strong> property is false. Any time the <strong>isCompleted</strong> property of a todo changes, the <strong>remaining</strong> property will recalculate.</p><p>The <strong>inflection</strong> property watches the <strong>remaining</strong> property and will update whenever <strong>remaining</strong> updates. If <strong>remaining</strong> is 1 the singular will be returned, otherwise the plural will be returned.</p><h4>Toggling between showing and editing states</h4><p>TodoMVC allows users to double-click on a todo to edit the title. To implement this functionality we will add an <strong>isEditing</strong> property to the todo controller which will be used to class the <strong>&lt;li&gt;</strong> element and provide an input for editing the todo.</p><p>Update <strong>app/templates/todos.hbs</strong> as follows.</p><pre>&lt;ul class=&quot;todo-list&quot;&gt;<br>  {{#each todo in model itemController=&quot;todo&quot;}}<br>    &lt;li {{bind-attr class=&quot;todo.model.isCompleted:completed todo.model.isEditing:editing&quot;}}&gt;<br>      {{#if todo.model.isEditing}}<br>        &lt;input class=&quot;edit&quot;&gt;<br>      {{else}}<br>        {{input type=&quot;checkbox&quot; checked=todo.model.isCompleted class=&quot;toggle&quot;}}<br>        &lt;label {{action &quot;editTodo&quot; on=&quot;doubleClick&quot;}}&gt;{{todo.model.title}}&lt;/label&gt;&lt;button class=&quot;destroy&quot;&gt;&lt;/button&gt;<br>      {{/if}}<br>    &lt;/li&gt;<br>  {{/each}}<br>&lt;/ul&gt;</pre><p>In <strong>app/controllers/todo.js</strong> add an <strong>editTodo</strong> action and an <strong>isEditing</strong> property.</p><pre>actions: {<br>  editTodo: function() {<br>    this.set(&#39;isEditing&#39;, true);<br>  },<br>  isEditing: false,<br>  //...<br>}</pre><p>This provides the <strong>editTodo</strong> method which switches the <strong>isEditing</strong> property to true. Now when you double-click on a todo, you are provided a blank input. Not quite what we are looking for.</p><h4>Accepting edits</h4><p>Now that we have an input, we need to make it functional. Now we will add the logic to focus on the input when it is visible, accept user input, and persist changes when the user presses <strong>Enter</strong>.</p><p>Generate a component which will be a modified implementation of a text field.</p><pre>ember g component edit-todo</pre><p>Modify the newly generated <strong>app/components/edit-todo.js</strong> to match the following.</p><pre>//...<br>export default Ember.TextField.extend({<br>  didInsertElement: function() {<br>    this.$().focus();<br>  }<br>});</pre><p>This automatically focuses on the element when it is inserted into the page.</p><p>Next, replace the static <strong>input</strong> element with the <strong>{{edit-todo}}</strong> component in <strong>app/templates/todos.hbs</strong>.</p><pre>{{#if todo.model.isEditing}}<br>  {{edit-todo class=&quot;edit&quot; value=todo.model.title focus-out=&quot;acceptChanges&quot; insert-newline=&quot;acceptChanges&quot;}}<br>{{else}}</pre><p>The method <strong>acceptChanges</strong> will be called if the user presses <strong>Enter</strong> or otherwise takes focus away from the input. The <strong>value</strong> of the input is bound to the <strong>title</strong> property of the model instance.</p><p>Finally, the <strong>acceptChanges</strong> method needs to be added to <strong>app/controllers/todo.js</strong>.</p><pre>//...<br>editTodo: function() {<br>  this.model.set(&#39;isEditing&#39;, true);<br>},<br>acceptChanges: function() {<br>  this.model.set(&#39;isEditing&#39;, false);</pre><pre>  if (Ember.isEmpty(this.model.get(&#39;title&#39;))) {<br>    this.send(&#39;removeTodo&#39;);<br>  } else {<br>    this.get(&#39;model&#39;).save();<br>  }<br>}<br>//...</pre><h4>Deleting a model</h4><p>Update the static <strong>&lt;button&gt;</strong> element in <strong>app/templates/todos.hbs</strong> to use an action called <strong>removeTodo</strong>.</p><pre>&lt;button {{action &quot;removeTodo&quot;}} class=&quot;destroy&quot;&gt;&lt;/button&gt;</pre><p>Add the <strong>removeTodo</strong> method to <strong>app/controllers/todo.js</strong>.</p><pre>//...<br>acceptChanges: function() {<br>  this.model.set(&#39;isEditing&#39;, false);</pre><pre>  if (Ember.isEmpty(this.model.get(&#39;title&#39;))) {<br>    this.send(&#39;removeTodo&#39;);<br>  } else {<br>    this.get(&#39;model&#39;).save();<br>  }<br>},<br>removeTodo: function() {<br>  var todo = this.get(&#39;model&#39;);<br>  todo.deleteRecord();<br>  todo.save();<br>}<br>//...</pre><h4>Adding child routes</h4><p>Adding child routes to the <strong>todos</strong> resource in the router will allow implementation of the filtered <strong>Active</strong> and <strong>Completed</strong> views that are linked at the bottom of the list. Use the generator to create a new <strong>index</strong> route within the <strong>todos</strong> resource.</p><pre>ember g route todos/index</pre><p>In addition to the route, the generator also gives us <strong>app/templates/todos/index.hbs</strong>. Move the entire todo list <strong>&lt;ul&gt;</strong> block to this file and replace it with <strong>{{outlet}}</strong> in <strong>app/templates/todos.hbs</strong>.</p><pre>&lt;section class=&quot;main&quot;&gt;<br>  {{outlet}}</pre><pre>  &lt;input type=&quot;checkbox&quot; class=&quot;toggle-all&quot;&gt;<br>&lt;/section&gt;</pre><p>Add the following to the <strong>extend</strong> block in <strong>app/routes/todos/index.js</strong>.</p><pre>model: function() {<br>  return this.modelFor(&#39;todos&#39;);<br>}</pre><h4>Transitioning to show only incomplete todos</h4><p>Create a new <strong>active</strong> route within the <strong>todos</strong> resource using the generator.</p><pre>ember g route todos/active</pre><p>This route will use the <strong>todos</strong> model with a filter applied. It will also render in the <strong>todos/index</strong> template that was created earlier. Add the following to <strong>app/routes/todos/active.js</strong>.</p><pre>model: function() {<br>  return this.store.filter(&#39;todo&#39;, function(todo) {<br>    return !todo.get(&#39;isCompleted&#39;);<br>  });<br>},<br>renderTemplate: function(controller) {<br>  this.render(&#39;todos/index&#39;, {controller: controller});<br>}</pre><p>The model function returns todos with the <strong>isCompleted</strong> property equal to false.</p><p>Modify <strong>app/templates/todos.hbs</strong> to replace the <strong>Active</strong> link with a <strong>{{link-to}}</strong> helper.</p><pre>&lt;li&gt;<br>  &lt;a href=&quot;all&quot;&gt;All&lt;/a&gt;<br>&lt;/li&gt;<br>&lt;li&gt;<br>  {{#link-to &quot;todos.active&quot; activeClass=&quot;selected&quot;}}Active{{/link-to}}<br>&lt;/li&gt;<br>&lt;li&gt;<br>  &lt;a href=&quot;completed&quot;&gt;Completed&lt;/a&gt;<br>&lt;/li&gt;</pre><h4>Transitioning to show only completed todos</h4><p>Create a new <strong>completed</strong> route within the <strong>todos</strong> resource using the generator.</p><pre>ember g route todos/completed</pre><p>Add the following to <strong>app/routes/todos/completed.js</strong>.</p><pre>model: function() {<br>  return this.store.filter(&#39;todo&#39;, function(todo) {<br>    return todo.get(&#39;isCompleted&#39;);<br>  });<br>},<br>renderTemplate: function(controller) {<br>  this.render(&#39;todos/index&#39;, {controller: controller});<br>}</pre><p>Modify<strong> app/templates/todos.hbs</strong> to replace the <strong>Completed</strong> link with a <strong>{{link-to}}</strong> helper.</p><pre>&lt;li&gt;<br>  &lt;a href=&quot;all&quot;&gt;All&lt;/a&gt;<br>&lt;/li&gt;<br>&lt;li&gt;<br>  {{#link-to &quot;todos.active&quot; activeClass=&quot;selected&quot;}}Active{{/link-to}}<br>&lt;/li&gt;<br>&lt;li&gt;<br>  {{#link-to &quot;todos.completed&quot; activeClass=&quot;selected&quot;}}Completed{{/link-to}}<br>&lt;/li&gt;</pre><h4>Transitioning back to show all todos</h4><p>Modify <strong>app/templates/todos.hbs</strong> to replace the <strong>All</strong> link with a <strong>{{link-to}}</strong> helper.</p><pre>&lt;li&gt;<br>  {{#link-to &quot;todos.index&quot; activeClass=&quot;selected&quot;}}All{{/link-to}}<br>&lt;/li&gt;<br>&lt;li&gt;<br>  {{#link-to &quot;todos.active&quot; activeClass=&quot;selected&quot;}}Active{{/link-to}}<br>&lt;/li&gt;<br>&lt;li&gt;<br>  {{#link-to &quot;todos.completed&quot; activeClass=&quot;selected&quot;}}Completed{{/link-to}}<br>&lt;/li&gt;</pre><h4>Displaying a button to remove all completed todos</h4><p>TodoMVC allows users to remove all todos that have been marked as completed with a button click. In <strong>app/templates/todos.js</strong> update the static <strong>&lt;button&gt;</strong> element with an <strong>{{action}}</strong>.</p><pre>{{#if hasCompleted}}<br>  &lt;button class=&quot;clear-completed&quot; {{action &quot;clearCompleted&quot;}}&gt;<br>    Clear completed ({{completed}})<br>  &lt;/button&gt;<br>{{/if}}</pre><p><strong>app/controllers/todos.js</strong> needs to be updated to add the <strong>hasCompleted</strong> and <strong>completed</strong> properties as well as the <strong>clearCompleted</strong> method.</p><pre>actions: {<br>  clearCompleted: function() {<br>    var completed = this.filterBy(&#39;isCompleted&#39;, true);<br>    completed.invoke(&#39;deleteRecord&#39;);<br>    completed.invoke(&#39;save&#39;);<br>  },<br>  //...<br>},<br>hasCompleted: function() {<br>  return this.get(&#39;completed&#39;) &gt; 0;<br>}.property(&#39;completed&#39;),<br>completed: function() {<br>  return this.filterBy(&#39;isCompleted&#39;, true).get(&#39;length&#39;);<br>}.property(&#39;@each.isCompleted&#39;),<br>//...</pre><p><strong>filterBy</strong> returns an <strong>EmberArray</strong> object which contains only items that return true. The invoke method is part of the EmberArray API and executes a method on each object in the array.</p><h4>Indicating when all todos are complete</h4><p>Update the static checkbox in <strong>app/templates/todos.hbs</strong>. This checkbox will indicate when all todos are complete.</p><pre>&lt;section class=&quot;main&quot;&gt;<br>  {{outlet}}<br>  {{input type=&quot;checkbox&quot; class=&quot;toggle-all&quot; checked=allAreDone}}<br>&lt;/section&gt;</pre><p>This checkbox will be checked when <strong>allAreDone</strong> is true. Implement <strong>allAreDone</strong> in <strong>app/controllers/todos.js</strong>.</p><pre>allAreDone: function(key, value) {<br>  return !!this.get(&#39;length&#39;) &amp;&amp; this.isEvery(&#39;isCompleted&#39;);<br>}.property(&#39;@each.isCompleted&#39;)</pre><h4>Toggling all todos between complete and incomplete</h4><p>The checkbox that was just implemented is useful, but it would be much more useful if it could toggle all of the todos between complete and incomplete.</p><p>To implement this, modify <strong>allAreDone</strong> in <strong>app/controllers/todos.js</strong>.</p><pre>allAreDone: function(key, value) {<br>  if (value === undefined) {<br>    return !!this.get(&#39;length&#39;) &amp;&amp; this.isEvery(&#39;isCompleted&#39;);<br>  } else {<br>    this.setEach(&#39;isCompleted&#39;, value);<br>    this.invoke(&#39;save&#39;);<br>    return value;<br>  }<br>}.property(&#39;@each.isCompleted&#39;)</pre><h4>Replacing HTTP-Mock with localStorage</h4><p>Adapters are easily swapped without affecting the overall application. Now that the application is complete, we will add a localStorage adapter, so the information can be persisted outside the session without a server.</p><p>Install the localStorage adapter and create a serializer to manage stringifying the JSON data for storage.</p><pre>ember install:bower ember-localstorage-adapter<br>ember g serializer application</pre><p>Go to <strong>Brocfile.js</strong> and add the following below the CSS imports which will include the adapter logic as a dependency.</p><pre>app.import(&#39;bower_components/ember-localstorage-adapter/localstorage_adapter.js&#39;);</pre><p>Now we need to make the application aware that we are using localStorage rather than REST.</p><p>Open <strong>app/serializers/application.js</strong> and change <strong>RESTSerializer</strong> to <strong>LSSerializer</strong>.</p><p>Open <strong>app/adapters/application.js</strong> and change <strong>RESTAdapter</strong> to <strong>LSAdapter</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bfe2d3c95e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>