12 Days of Posts: Day 4 – using call and apply

We have seen some ways that we can take advantage of JavaScript’s functional roots. This theme will continue for this post as we will look at call and apply.

Call and apply are very similar. Both methods will execute the function, set the this value and pass in parameters. Call does this by having the parameters each explicitly defined while apply takes an array of parameters. Here is an example using our trusty add function and whatIsThis.

function add(x, y){
  return x + y;
}

function whatIsThis() {
  console.log(this);
}

console.log(add.call(undefined, 1, 2));
//returns 3
console.log(add.apply(undefined, [1, 2]));
//returns 3
console.log(whatIsThis.call({prop: 'test'}, null));
//returns Object {prop="test"}
console.log(whatIsThis.apply({prop: 'test'}, null));
//returns Object {prop="test"}

We can see the differences in execution, but the result will be exactly the same.

These examples are arbitrary so let’s build a little less arbitrary example. Let’s imagine that we have a comparing object that has a function to make a comparison. We want to make it so that the comparison function can be changed at a later point in time. We can use apply to make this easy. Here is that example.

var newCompare = function(a,b) {return a>b;}

var comparer = {
  compareFunc: function() {
    return false;
  },
  compare: function compare(a, b) {
    return this.compareFunc.apply(this, [a, b]);
  }
}

console.log(comparer.compare(5,1));
//returns false
comparer.compareFunc = newCompare;
console.log(comparer.compare(5,1));
//returns true

The compare function just executes another function. This means that we can change it out whenever we need to. The best part is that the new function does not need to know about the current object as it will all of its context passed to it by apply.

I have a real world example of this in my Webcam library. The library has a draw function, but we can change it out whenever we want. The new function will have access to a canvas, the 2d context, the 3d context, and the video stream. We can see the code on line 130 in video.js.

Here are all the examples in jsFiddle.

12 Days of Posts: Day 3 – using bind with a function

We are already at day 3. We are continuing with JavaScript and building on what we have already covered. We are going to cover the bind method of the function object.

Bind is used to define what this is inside of a function. It will return a new function (there is that ‘functions are a first class object’ idea again!) and not modify the current function. Let’s look at an example. Here is a simple function:

function whatIsThis(){
  console.log(this);
}
whatIsThis()
//this will return the window object

The default this value for an anonymous function will be the window object. We will now bind a new value for this using bind:

var newBoundWhatIsThis = whatIsThis.bind({property: 'Test'});
newBoundWhatIsThis();
//this will return Object {property: "Test"}

We have changed the value of this with bind. This will allow us to build functions that can operate on many different objects as long as the objects all have the same properties. Here is an example.

var josh = {name: 'Josh'};
var brian = {name: 'Brian'};
function outputName(){
  console.log(this.name);
}

outputName.bind(josh)();
outputName.bind(brian)();

Here outputName can operate on both objects.

Finally we will use bind to partially apply parameters. This is the same concept as the last post. Any other parameters passed into bind will be prepended to the list of arguments when executed later. Here are the examples from the last post, but this time with bind.

var boundAddOne = add.bind(window, 1);
boundAddOne(5);
//will return 6

var boundAddTen = add.bind(undefined, 10);
boundAddTen(5);
//will return 15

The add function does not do anything with this so it does not really matter what we use. We then pass in the first parameter so that a new function will be returned that will accept one parameter.

Here are all the examples on jsFiddle

12 Days of Posts: Day 2 – Partial application of a function

This day’s post is a continuation of the last post. In the last post we covered that a function can return a function, but we did not cover any use cases. This post will discuss a very useful one.

We have an add function:

function add(x, y){
  return x + y;
}

We can partially apply one of the parameters and return a new function. To reinforce what this means we will look at an example.

function partiallyApply(param, func){
  return function(nextParam){
    return func(nextParam, param);
  }
}

var addOne = partiallyApply(1, add);

The variable addOne takes the add function and partially applies one of the parameters (y is now always 1). When we execute partiallyApply we bind the first parameter and return a new function which allows us to bind the other parameter later. This means we can do this:

addOne(5);
//returns 6
addOne(10);
//returns 11
var addTen = partiallyApply(10, add);
addTen(5);
//returns 15

What good is this? Well we essentially are passing in parameters over two separate points in time. I had a problem where I needed an index for an item in a list and the event object. The issue was that I did not have these two things at the same time. The event object is only created in response to an event. I partially applied the index first which returned a function that would accept the event object. I have the code in the react_components.js file in my Where to eat repository.

The next post will continue the JavaScript theme.

12 Days of Posts: Day 1 – Functions can return functions

I am attempting to do something a little different. Right now everywhere you go there is something related to Christmas. This inspired me to challenge myself to write 12 short posts before Christmas. Here is the first.

Functions can return functions

In JavaScript functions are first class objects. For our purposes here that means that functions can be returned from other functions, used as parameters for other functions, and the value stored in a variable.

This means we can take a simple function like this:

function add(x, y){
  return x + y;
}

This is a completely arbitrary function but we will build another function to return this one.

function returnAFunction(){
  console.log('In returnAFunction');
  return add;
}

This just has a console call to let us know when we execute it and then it returns our add function.

Here are some things that we can do with this now:

var returnedAdd = returnAFunction();
//console logs In returnAFunction
returnedAdd(1,2)
//the output would be 3
returnAFunction()(2,2)
//console logs In returnAFunction
//the output would be 4

First we capture the returned function as returnedAdd. We can then use that as if it was our add function. Next we execute returnAFunction and then immediately execute the returned function. This demonstrates the first class nature of functions. Functions are not some special type that must be defined first and then executed. We can pass functions around just like we would any other object.

Why would we do this? The post tomorrow will build on this idea and answer why would we do this.

WordPress on Docker: the videos

https://github.com/johanan/Dockerized-Wordpress-the-Correct-way

I have created a three video series on running WordPress in Docker. This is different than my previous posts on Docker and WordPress. The posts I had written before focused mainly on my journey of moving my site to Docker. This means that many pieces were directly tied to my implementation. These videos and code does not have that requirement. The repository can be used to create a WordPress site from scratch and having running in the cloud in just a few minutes.

WordPress on Docker the Correct way

I keep using the qualifier “the Correct way”. I have explained this in other posts, but I will reiterate it here succinctly. There are quite a few WordPress on Docker containers out there already that run everything in the same container. These containers will allow you to get a site quickly, but everything is tightly coupled. The way I have built it is that the entire implementation of the containers does not matter. As long as you have a backup you can create your site from scratch again. This makes it really easy to run a test site in Vagrant for example. MySQL has an update, destroy your entire site and rebuild. I read a great comment on Hacker News a few days ago. This is paraphrased.

Don’t treat your servers like pets. Treat them like cattle.

This means do not get attached and tweak settings. The entire site should be a repeatable build that starts from scratch. This blog is already on it’s sixth or seventh iteration of changes because I can create my blog from a backup in about seven minutes. This opens the freedom to test and tweak as any complete screw up is fixable in just a few minutes.

Full stack WordPress

The site that is built from my repository can terminate SSL with Nginx and cache your requests with Varnish. This means that you get performance right out of the box. This is important because a WordPress site with many plugins running can be quite slow. When you run my WordPress setup you get a four layer application all built in Docker. The layers are reverse proxy, HTTP caching, a PHP application server, and a database server.

In addition to this you will learn about server provisioning with Ansible. Ansible allows you to take a server in any state and move it to the state you want. This means it makes sure you have the users, packages, and files on the server. Ansible lays the groundwork that you build Docker on. Continue reading “WordPress on Docker: the videos”

WordPress Docker containers

This post will cover what each container in our Dockerized WordPress setup does. This should not be viewed as a standalone post as there is a video playlist that covers more. The playlist demonstrates how you can quickly and easily bring up a Dockerized WordPress install.

First we will start with an image that will explain so much with so little.

Shows how each container links to the others

Yes, there are six different containers. This is so that we can keep each container with a single purpose and even a single process in most cases. We can easily replace and upgrade each container this way. I have blogged on this previously and will not iterate everything here. We will look at each container and any interesting things about each. Let’s get started. Continue reading “WordPress Docker containers”

How to link Docker containers together

This is the third post in a series about moving my WordPress blog into the cloud using Docker.

Download the src(github).

Blog Post Series

At this point we have a bunch of docker images, but no docker containers running. We will fix that in this post. We will look at docker-compose and how it orchestrates bringing up all of our docker containers. Then we will look at some administrative tasks in docker. This includes backing up the site and keeping logs.

Bringing up Docker containers with docker-compose

Docker-compose is a tool from Docker that allows us to define how each container will fit in our application. It makes for a single command to get everything up and running. Docker-compose should already be installed on our target machine by Ansible. First thing we will do is look at our docker-compose.yml which configures everything. Continue reading “How to link Docker containers together”

WordPress and Docker the correct way

Download the src(github).

Blog Post Series

We now have a good foundation to build our WordPress site off of. Docker is installed and ready. We will quickly cover why Docker, some best practices, and finally the actual how of our Docker containers. Much like the previous post, this is not designed to be an introduction to Docker. There are literally thousands of intro to Docker articles and by the time I publish this that number will have doubled. Sign up to any tech newsletter and you will easily see five “Intro to Docker” articles every week. If you want an introduction, go to the official Docker site and you there is an interactive tutorial.

I would also like to point out that if you have followed along or forked my Github repo, you will have a Vagrant machine that has Docker on it by running:

$ vagrant up
$ ansible-playbook -i ./.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory ../ansible/docker.yml

You can then run vagrant ssh and have a completely disposable Docker virtual machine.

Why Docker

The most honest answer I can give to this is that I needed to upgrade my Linux server. I was running Ubuntu 12.04 which is three years old and one LTS release behind. The server was working and I did not want to setup a new one. I had been using Ansible, so I knew I was going to use that. In fact in the beginning I was just going to create an Ansible playbook to install my WordPress stack. I, of course, had heard about Docker and wanted to build something with it. After reading about Docker I decided it would be the most extensible option.

We will discover why in this post. Docker allows us to easily rethink and rebuild our stack from the ground up. Want Apache instead of nginx? Swap it. New version of nginx? Swap it. MariaDB instead of MySQL? You get the idea. This would be very difficult to do without provisioning a brand new server. We also will have a test site that we can run locally that is almost *literally* the exact same as production.

The CORRECT way to use Docker

There are some strong opinions on how a Docker container should be built. I am in the “As few processes as needed, ideally one process” camp. Doing this comes with difficulties and I will list out the issues and what we can do about the issues. Continue reading “WordPress and Docker the correct way”

My talk on React

This is a talk I gave for a local Meetup about React. It is called ‘Why I like React’. I cover the basics of building React components. Then I spend some time talking about functional programming. Finally I wrap it all together to show how React is functional in nature. The final demo shows how to ‘think in React’.
Continue reading “My talk on React”

A trip to Europe

I have been away for the last two weeks on a wonderful trip to Europe with my wife. The planning, the actual trip, and the recovery has slowed down the writing of my posts. I was hoping to have the Docker post done before I left, but it did not work out.

This is not a travel blog, but I do want to note a few things I learned on our trip. The things I learned are not what spots to go see as people like Rick Steves already has that covered better than I could ever do. They are more specific to things about each city or country that would have been nice to know. Here is where I went and what I learned.

Google Maps

I just want to make a quick shout out to Google Maps. It was indispensable on our trip. First and the most obvious was using it to get around every city. We would use GPS and the map of the city to plan out a walking path and/or determine if it was better to call an Uber. Second is Google Maps public transportation. The app will show you which subway line to use (using the correct color), which direction, and how many stops. We would search it and then take a screenshot to use later. This was very useful. Here is an example.
Google Maps Paris Metro Example

Airbnb in Europe

We used Airbnb(referral link) for every night except for the final night. Airbnb gives you the best apartment and location for the value. Instead of staying in a hotel that looks like every other hotel you have stayed in, why not stay in a local’s apartment? I recommend only using the listings that have good reviews as a stay could be ruined by a poor host.

An important thing to remember when booking is that you will not have the exact address of the apartment. You will only have a neighborhood (although it is precise enough to make plans). It is not until you have booked the apartment will you receive the address.

Before booking you should ask about things like towels and if you can store your luggage after checkout. I found that most hosts try to be cooperative and flexible. Once you have booked and the date is approaching you should message them to let them know an approximate time a few days before. Finally let them know when you are close, for example you are at the train station, on the day of.

London

We flew to London from O’Hare on Virgin Airlines. I would definitely recommend Virgin. I have flown a few times before and Virgin was the best airline I have used. It was the best 8 hours I have spent in an airplane in my entire life.

Getting around London

The Tube system is great in London. I recommend purchasing an Oyster card as it will halve your fares and has a ceiling on how much can be charged. We did not get one at first and because of this we wasted many pounds. Continue reading “A trip to Europe”