Jan Carlo Viray React · Angular · Node · Go · SQL · NoSQL · Cloud · Entrepreneurship

A year from now you’ll wish you started today — Karen Lamb

LinkedIn ·  Twitter ·  Github

How to Find Files Containing Specific Text

How to find files containing a specific text recursively in Unix / Linux system? I typically use grep like this:

grep -rnw "pattern" /path/to/file

Companies Using Docker

Going with the flow of “companies using [insert tech]”, here are the companies using Docker. Big companies with the need for scalable and distributed systems seem to have adopted docker. Though there are many critics talking about Docker not being production-ready, I am impressed to find that a global financial service corportation such as ING using Docker containers to drive 500 deployments a week.

Companies Using Angular

To be fair, it would be nice to see my other favorite stack have an updated list of companies using it. Here’s the list of companies using AngularJS, in order of recently found to older

Companies Using React

I am quite impressed at the adoption of React.js (it is not 1.0 yet!). From my search and experience working with both Angular and React, as well as networking within the field, I personally see that (with exceptions) Angular.js is the de-facto framework chosen by early startups while React.js is the de-facto framework chosen by more established companies/startups. Personally, I love both. I find Angular.js more fun to work with (at the cost of occasional frustrations), while I find React.js more peaceful and less stressful framework to work with, though at the cost of more typing and boilerplate code to write

React Props in State an Anti-Pattern

Passing the initial state to a component as a prop is an anti-pattern because the getInitialState method is only called the first time the component renders - and never called after that. This means that if you re-render the parent, while passing a different value as a prop, the component will not update the UI because it will keep the state from the first time it was rendered. This will make the application very prone to errors.

Solution? Make the components stateless. They are easier to test because they render an output based on an input. Have the parent component contain the passed-in data as its own state, then if the state changes, it re-renders its children, while passing in everything they need through props.

What does this look like in React?

React.js Lessons Learned

React.js lessons learned and some opinionated best practices. This is an ongoing compilation and in-progress work of everything I have learned from developing in React.js

Basic Component Organisation

React.createClass({
    propTypes: {},
    mixins: [],

    getInitialState(){},
    getDefaultProps(){},

    componentWillMount(){},
    componentWillReceiveProps(){},
    // Store removeChangeListener
    componentWillUnmount(){},
    // Third-party code initialization here...
    // Store addChangeListener here...
    componentDidMount(){},

    _parseData(){},
    _onSelect(){},
    _onChange(){},

    render(){}
});

Flux Pattern Tips

Stores

  • Stores don’t have to just represent data. They can also represent application state, whether modals are shown/hidden, or if user is online/offline, etc.
  • Stores can and probably will need to use data from other stores. Use waitFor method in dispatcher.
  • Stores should not contain the logic to fetch themselves on a server; it is better to use DAO (data access objects) that are thinly wrapped API objects to get the data.

Actions

  • Actions should be split into two types: view actions and server actions. This will separate user interaction such as clicking a button from retrieving data.
  • Actions should be fire and forget and must not have callbacks. If you need to respond to the result of an action, you should be listening for a completion or error event This enforces data being kept in the store and not on a component.

React Best Practice Compilation

Here is a compilation of best practices I have learned and compiled building React.js applications. Feel free to add to this content by visiting my blog source and sending a pull request.

jQuery vs React

jQuery Style

Event Handler <—> Change DOM

React.js Style

Event Handler –> State –> render()

  • Event handler changes state. React does a diff in virtual dom and renders.

Properties vs State

  • Properties are immutable.
  • State is mutable. State is only reserved for interactiviy. Therefore, anything that is going to change, it goes into State. State should store the most simplest values.

  • Props in getInitialState is an anti-pattern.
  • Avoid duplication of “source of truth” which is where the real data is. Whenever possible, compute values on the fly to ensure they don’t get out of sync later on and cause maintenance trouble.
  • It is often easier and wiser to move the state higher in component hierarchy
  • You should never alter state directly. Call it through setState

  • Most importantly, the state of a component should not depend on the props passed in (state as in state of the component - not of the app). *A huge “code smell” is when you start seeing the state depending on the props. For example, this is not good: constructor(props){ this.state = { fullName: ${props.first} ${props.last}}}. These guys should go in the render

  • Leave calculations and conditionals to the render function.
  • Note that everytime state is changed, render is called again.

How to share/sync directory inside Vagrant

To share directories, add this to your config. config.vm.synced_folder "host/relative/path", "/guest/absolute/path". Below is an example within a full configuration file.

Vagrant.configure(2) do |config|
	# note that you can have this config multiple times but
	# it should only be used for source code since there is
	# heavy performance penalty on heavy I/O such as database files

	# first path is the host's path, which can by absolute
	# or relative to project's root directory

	# second path is the guest path, and it must be absolute.
	# It will always be created if it does not exist.
	config.vm.synced_folder ".", "/vagrant"

	config.vm.synced_folder "./some/dir/one", "/one", create:true
	config.vm.synced_folder "./some/dir/two", "/two", create:true

	# note that you can also add type. NFS is the faster
	# bidirectional file syncing. In order for this to work,
	# the host machine must have nfsd installed. It comes
	# preinstalled on OSX and is a simple package install on Linux
	config.vm.synced_folder "." "/vagrant", type: "nfs"

	# owner/group
	config.vm.synced_folder "." "/vagrant", owner: "root", group: "root"
end

How to install Vagrant and VirtualBox

Vagrant provides easy to configure, reproducible, and portable work environments controlled by a single consistent workflow to help maximize the productivity and flexibility of you and your team. If you’re a developer, Vagrant will isolate dependencies and their configuration within a single disposable, consistent environment, without sacrificing any of the tools you’re used to working with (editors, browsers, debuggers, etc.). Once you or someone else creates a single Vagrantfile, you just need to vagrant up and everything is installed and configured for you to work. To get started, download Vagrant and VirtualBox.

Quick Start

vagrant init hashicorp/precise32
vagrant up

Sample Working Vagrantfile


Create a file and call it Vagrantfile

Vagrant.configure(2) do |config|
	config.vm.box = "precise64"
	config.vm.network :forwarded_port, guest: 80, host: 8800
	config.vm.provision "shell", path: "provision.sh"
end

Once you have that, run this command

State is an Anti-Pattern

As much as possible, do not use state at all. According to this comment, state should never have been in the library in the first place. It seems that if Flux was introduced in conjunction with React initially, state would not even exist. It seems that state was used to allow react to function by itself without flux. If a React component must have side-effects, it must use Flux actions instead of having state. Components ideally should have no state at all.

New Portfolio Site

I finally put my portfolio site at jcviray.com. I’m currently available for freelance/remote work and I specialize in Angular, React, Node, Mobile, Responsive. Let’s connect at linkedin! Also, let’s connect at twitter.

How To Reduce Docker Image Size?

Docker containers built from Dockerfiles can grow very big in size. There are a few simple tricks to cut back on some of the container fat. Here are some of the ones I’ve used. ## Clean the APT RUN apt-get clean RUN rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* ## Flatten the Image ID=$(docker run -d image-name /bin/bash) docker export $ID | docker import – flat-image-name Then, you can save it for backup too. ID=$(docker run -d image-name /bin/bash) (docker export $ID | gzip -c > image.tgz) gzip -dc image.tgz | docker import - flat-image-name

What Does Docker Link Do?

How does Docker link container? What happens during the process? Docker creates a secure tunnel between the containers that doesn’t need to expose any ports externally on the container. Notice that there is no need to use either the -P or -p flags.

Docker exposes connectivity from the source container to the recipient container in two ways:

  • Environmental Variables
  • Updating the /etc/hosts file

Environment Variables

Docker creates several environment variables when you link containers. It exposes all environment variables originating from Docker from the source container, which includes ENV commands, -e --env and --env-file options on the docker run command when the source container is started.

Docker sets an <alias>_NAME environment variable for each target container listed in the --link parameter. For example, if a new container called web is linked to a database container called db via --link db:webbed, then Docker creates a WEBDB_NAME=/web/webdb variable in the web container.

Docker also defines a set of environment variables for each port exposed by the source container. Each variable has a unique prefix:

<name>_PORT_<port>_<protocol>

The <name> is specified in the --link parameter (i.e.: webdb) The <port> number is the one exposed The <protocol> is either TCP or UDP

Docker uses this format to define environment variables such as:

The prefix_ADDR variable contains the IP Address from the URL, for example WEBDB_PORT_8080_TCP_ADDR=172.17.0.82. The prefix_PORT variable contains just the port number from the URL for example WEBDB_PORT_8080_TCP_PORT=8080. The prefix_PROTO variable contains just the protocol from the URL for example WEBDB_PORT_8080_TCP_PROTO=tcp.

Note that if the container exposes multiple ports, an environment variable set is defined for each one.

Updating the /etc/hosts file

In addition to the environment variables, Docker adds a host entry for the source container to the /etc/hosts file. Here’s a sample entry:

$ docker run -t -i --rm --link db:webdb training/webapp /bin/bash
root@aed84ee21bde:/opt/webapp# cat /etc/hosts
172.17.0.7  aed84ee21bde
. . .
172.17.0.5  webdb 6e5cdeb2d300 db

Notice two relevant host entries.

Docker Commands Cheat Sheet

A summary of commands I have come across while using Docker in my projects.

Note: if you are using Boot2Docker, then do not type sudo otherwise you will get an error

Tips

  • You can replace [containerID] with [containerName]. You only typically need 3 characters from [containerID]
  • Append –help if you want more information about the command, like docker run --help
  • Note that Containers are not the same as Images. Containers are like instances.
  • If you are using boot2docker, it might cause some issues such as docker server being unresponsive. Restart boot2docker with boot2docker restart to fix issues such as DNS and etc.
  • Containers are process-driven, so once the process is done, it will exit (this might take a while to get used to).
  • to “enter” a container that is currently running in the background as a daemon, run docker exec -it [container] /bin/bash

Commands

General


Check Docker Version

sudo docker version

Image Info


Search For Available Images

sudo docker search [imageName]

List Locally Saved Images

sudo docker images

Pull and Cache Images from Remote

sudo pull [imageName:tag]

  • note that if you do docker run ubuntu ... it will run this command if you do not have ubuntu stored locally
  • it is recommended to pull with a specific tag

Example

# search for ubuntu
sudo docker search ubuntu

# pull ubuntu v14.04
sudo pull ubuntu:14.04

Docker Run

What happens in a docker run command?

More specifically, what happens when you run this code: sudo docker run -i -t ubuntu /bin/bash?

Pulling from docs, this is what docker does:

ReactJS Overview

One unique selling points is that ReactJS can also be rendered server side and can work with client/server inter-operably.

Why React?

render() is just regular javascript. You get full power of JS in your rendering code and not constrained by what your templating language is capable of. You can use map, reduce, filter, groupBy and etc.

It is fast (as fast or even faster than native DOM).

You don’t have to give up flexibility for simplicity. You can have

With Flux, it pushes towards unidirectional flow, reducing complexity and increasing predictability.

I like how the jsx and component (not business!) logic is in just one file.

“Suffice to say, that in many cases React is much faster than angular. Develop with angular enough, and you will run into situations where the dirty-checking digest cycle is too slow for the requirements of your application. For these cases, a rather painless solution is to use ngReact. ngReact allows you to include React components inside of an angular application. The first React component I ever built was a re-write of a 20-month calendar widget originally written in angular. The rewrite took about a day which is a testament to the rather easy learning curve of React and the simplicity of ngReact. I didn’t even attempt to do any shouldComponentUpdate() optimizations in the React component and it was several times faster than it’s angular counterpart.” - https://medium.com/@gilbox/how-can-react-and-flux-help-us-create-better-stronger-faster-angular-applications-639247898fb

components

  • are the smallest, yet most fundamental part of React. They are similar to widgets and modules.
  • when building in React, you need to think of it in terms of the smallest possible components you can define.

lifecycle of components

Mounting

Basic Docker Overview

Docker is a growing technology for and spreading like wildfire. Time to delve in the basics and apply it on your projects!

Docker is here to offer an efficient, speedy way to port applications across systems and machines. It is light and lean, allowing you to quickly contain applications and run them within their own secure environments (via Linux Containers: LXC).

“Docker is an open platform for developing, shipping and running applications. Docker is designed to deliver your applications faster. With Docker you can separate your applications from your infrastructure AND treat your infrastructure like a managed application. Docker helps you ship code faster, test faster, deploy faster, and shorten the cycle between writing code and running code.” - docker.com

Main Docker Parts

  • docker daemon is used to manage docker (LXC) containers on the host it runs. The user does not directly interact with the daemon, but instead through the Docker client.
  • docker CLI is used to command and communicate with the docker daemon in the form of the docker binary.
  • docker image index is a repository for docker images

Main Docker Elements

Docker Containers

The entire procedure of porting applications using docker relies solely on the shipment of containers. Docker containers are basically directories which can be packaged (tar-archived) like any other, then shared and run across various different machines and platforms.

The containment here is obtained via Linux Containers (LXC).

Docker containers allow: application portability, isolating processes, prevention from tempering with outside, managing resource consumption.

Think of containers as a process in a box. The box contains everything the process might need. It has a filesystem, has system libraries, shell and etc.

By default, a container that you have pulled from the Registry will not be running. You can start a container using docker run [imagename] [command to run plus args]. After the container has executed the command, it will stop the container.

Whatever the command does will not be forgotten within the image. If you install something through apt-get, it will not be forgotten. However, it will not yet be persistent.

To save a persistent change, you can ‘commit’ it by running docker commit [id] [new/name]. You typically only need to put in the first two or three characters of the ID of the container. To find the ID, run docker ps -l.

The commit will be a new repo, and will return a new image ID.

To check running containers, use docker ps.

To inspect a container, run docker inspect [containerId].

Disable Terminal Line Wrap

I’ve gotten a bit annoyed with terminal wrapping long lines. I’ve been using less for a long time already, but did not know the -S option, or “–chop-long-lines”.

this_command_produces_wide_output | less -S

Bam! Use horizontal arrow keys to view the rest of the line.

Run Terminal in Docker

docker run -i -t ubuntu:latest /bin/bash

ES7 Async and Await Simplified

Promises have been the predominant solution to the “callback hell” issue with JavaScript, but starting with ES6, and now ES7 it is slowly being tucked behind the scenes to pave way for async and await.