Understanding Polymorphic Associations in Rails

When first trying to get an understanding of polymorphic associations in Rails, I was completely lost. At this point in my learning curve, polymorphic associations are a high-level concept in Rails which allows the programmer to reuse a single model to be useful for other models. It’s difficult to describe without an example. So… here we go.

An example of a polymorphic association is as follows. Let’s say you’re building a sports history database. Baseball players and basketball players are both athletes, but you want to be able to keep the baseballers separate from the basketballers. One way to do that is to create an Athletes model.

The Athlete model would be a way to tie the sports together.

Coding The Polymorphic Association

This requires a migration where we connect the athletes with the sports they play:

rails g migration AddSportToAthlete sport_id:integer sport_type:string

First we set the polymorphic association model:

class Athlete < ApplicationRecord
  belongs_to :sport, polymorphic: true
end

Then we assign that association to the baseballers and the basketballers:

class Baseballer < ApplicationRecord
  has_many :athletes, as: :sport
end

class Basketballer < ApplicationRecord
  has_many :athletes, as: :sport
end

irb rbenv: pry: command not found – FIXED

$ irb
rbenv: pry: command not found

The `pry' command exists in these Ruby versions:
  2.3.1

I was having the issue in which I was attempting to test code using irb and the irb command wasn’t opening the Ruby REPL.

Apparently, pry was interrupting my usage of irb.

To fix it, I just updated pry:

gem install pry
irb rbenv: pry: command not found

Now it’s updated and working correctly. Here are my related software versions:

$ rails -v
Rails 5.2.1
$ pry -v
Pry version 0.11.3 on Ruby 2.5.1
$ irb -v
Pry version 0.11.3 on Ruby 2.5.1

The 12-Factor App – Notes and Reflections

What follows are my own notes and summations after reading what makes a 12 factor application. Reading this has been a great glimpse into why we do certain things.

I’m currently working with a friend (Ginger Nomad) on building a web app. He is the expert so I follow his lead even though it seems needlessly complex at times.

After reading this, I get it. Why obfuscate the config.js file and the .env files with these additional node modules? Because it’s smart. This document helped me get off the, “Why are we making this so complex”-train.

That’s the why. Here are my notes.

I. Codebase

A deployment is a running instance of an application. This of a deployment like a play. Trey and Matt wrote the Book of Mormon, but the Eugene O’Neill Theatre puts an instance of the play on when they perform it.

Each application should have a single codebase. If multiple apps make up a software project, that isn’t an app. It’s a distributed system made up of apps. Each app that makes up a distributed system should be a 12 factor app on it’s own.

II. Dependencies

A 12 factor app doesn’t depend on system-wide packages. When building a 12 factor app, I should be able to send a new developer the project and they should be able to run it with a working version of node and a simple npm install XXX command.

III. Config

12  factor apps should contain everything that is likely to vary between deploys in a single place. This is often the .env file for us NodeJS developers. This file will include things like:

  • Database Connection Keys – URI, Username, Password, etc.
  • External service credentials – API keys for example
  • Canonical values like hostname – We use path – npm

When we build NodeJS apps, we use the env – npm package to put all the config information in one place.

They warn against storing config variables as constants across the whole application. I’m unsure if this is for security reasons, or if it’s because they just want all the config variables in one place. When deploying multiple instances of an application, it makes sense to have all that data in one place for easy (or algorithmic) editing.

IV. Backing Services

There should be no distinction between local and third party services. To me, this means the app should be able to swap a local MongoDB with a database hosted on mLab, for example, without changing the codebase.

Other backing services could include Amazon S3, Google Maps, Twitter, and Postmark to name a few.

Why? Imagine you’re running an instance of your application and the server gets hit by a bus. That would cause the server to stop working and the database to explode into an inferno. How would you clean it up?

Well, because your backing services are all connected the same way, you would just adjust the config file and create a new instance of the database from backup. You could be back up and running in 10 minutes.

V. Build, Release, and Run

12 factor application development calls for separated build, release and run stages.

  • Build Stage – Where you transform a code repo into an executable bundle. This is where the server fetches dependencies and compiles the assets.
  • Release Stage – Combined build procedure with deploy’s config resulting in a release which can actually be run by humans.
  • Run Stage – Here you run the app by running it’s processes against a selected release. Otherwise put, you use it. Click away brave soldier!

VI. Process

The document calls for executing the app as one or more stateless processes. These processes should be stateless and share-nothing. All persistent data should be stored in a backing service like a database.

To be honest, I don’t entirely get this. I relate it to the way Redux adjusts state in single bursts, but I’m unsure if that is a worthwhile comparison (let me know in the comments below if you know more about this).

VII. Port Binding

12 factor apps should be self-contained and should not rely on runtime injections of a web-server into the execution environment.

I don’t know what self-contained means exactly. It’s possible that NodeJS was built to be self-contained so I’ve never experienced this problem. When building a Node application, one of the first steps is to set the port for the server to listen from.

VIII. Concurrency

Processes are first-class citizens.

In 12 factor apps, the processes share nothing and are horizontally portionable so adding concurrency is simple and reliable.

To me this is like… returning books at the library. The application is the library and it can put a box out to collect returned books. If the library has an especially busy day of book collection, they can just put out an additional box. That way the two boxes are accepting books at the same time, but they books aren’t getting mixed up or returned out of order….

Does that make sense? If you have something to add, please do so in the comments below.

IX. Disposability

Robustness in applications is maximized with graceful shutdowns and fast starts. Therefore, 12 factor apps should be able to be stopped and started at a moments notice.

SIGTERM is the signal from a process manager which should be able to shut down your application.

Idempotent – A property of an operation that means the operation can be applied multiple times without changing the result beyond the initial application.

In the article they mentioned a database technology called CouchDB. I’d like to return to it one day. I love the idea of idempotent operations.

X. Development and Production Parity

Development, staging and production should have similar execution environments. Also, they time distance between a developer making a change and the production side of the app seeing that change should be short.

No more working on code for six months and launching it once. Continuous development is an important characteristic for 12 factor apps.

XI. Logs

12 factor apps should treat logs as event streams. Therefore a 12 factor app should not be concerned with routing or storing it’s output stream.

XII. Administrative Processes

Administration processes should be one-off processes.

Administration code should also ship with the application code and run against a release using the same codebase and config process.

12 Factor App Checklist

  • Does your application require a single code base?
  • Are all required external dependencies loaded into the app? Can a new node developer run ‘npm install’ and get it working?
  • Are all your config variables and settings in a single file?
  • If you pushed your codebase to an open source repository like GitHub, would your config information be automatically hidden?
  • Does your codebase interact with backing services without editing the codebase?
  • Are your build, release and runs stages strictly separated?
  • Are your application’s processes stateless? Do they share nothing with other processes? Is your backing service stored in persistent backing services?
  • Does your app NOT require injections of a webserver?
  • Have you bound processes to a specific port?
  • Does your app NOT daemonize or write PID files?
  • Can your app be started and stopped at a moments notice without losing important data?
  • Are the development and production environments similar?
  • Does your app not care if it’s storing logging output streams?
  • Does your admin code ship with the application? Is the admin code connected to the release number, the codebase and the config file?

If you answered yes to tall the above questions, it seems you have a 12-factor app. Please let me know what it is in the comments below as I’d like to see what you’re working on.

Learn HTTP – My Notes

I’m trying to write a server/API that interacts with client side API. To do that, I need to learn HTTP in depth. These are my notes from doing a deep dive into how HTTP works.

I wish there was a good tutorial where someone teaches you how to write a bunch of server integrations using HTTP requests quickly. I love to learn using muscle memory, but information related to HTTP is always very technical and dense.

My goal is to write a web app where server side Express code speaks with a SurveyJS based client side front-end efficiently.

Learning HTTP is an important step to achieving that.

WebDev Cave

HTTP Explained (Video)

It was helpful to watch this video closely before moving onto the more dense TutorialsPoint HTTP tutorial. It’s a bit boring, but we learn some important things and it preps the learner to go deeper. Specific valuable notes include:

  • HTTP is the most used protocol in the world
  • HTTP = The internet’s Postal Service
  • TCP/IP based protocol
    • To me, this means HTTP is just a checklist for communication across the internet
  • Connectionless protocol – The request for information and the response are not part of a single connection. Each request and response is a fresh connection between client and server.
  • The most reliable way to move data on the web

Request – Response Cycle

The user generates a request (HTTP Message). The request is sent to the server. The client then disconnects and waits for a response.

The server processes the request, prepares the response, establishes the connection again with the user and sends back the response in the form of a HTTP message. The server disconnects after the HTTP message is sent.

What an HTTP Message Looks Like

HTTP Request

Start line

  • METHOD – describes what to do.
    • GET | POST |DELTE | UPDATE (See below for what these all do)
  • URI – This describes where the resources we want are are.
  • Version – This tells us what version of HTTP to Use (e.g. HTTP/1.0)

Header – Key value pairs that describes language, host and the media type we are using. For example:

  • Host = www.example.com
  • Accept-language = en-us
  • Accept: text/html (image/gif, text/html etc…)

HTTP Response

Start line

  • Version – This tells us what version of HTTP to Use (e.g. HTTP/1.0)
  • Status Code – How the connection faired. See below for a more in depth description of status codes. (e.g. 404 = fail or 200 = success)

Header – Key value pairs that describes language, host and the media type we are using. For example:

  • Host = www.example.com
  • Accept-language = en-us
  • Accept: text/html (image/gif, text/html etc…)

Body – A path to where the response data is. An example would be __dirname + /events

Tutorials Point HTTP

TutorialsPoint HTTP

This HTTP tutorial is very helpful because it lays out the specifics of the technology. HTTP is actually quite simple.

HTTP Status Codes

Status codes always confused me, though after reading the tutorial, they make a lot more sense. Here’s how they break down.

  • 1xx: Informational – Status codes that begin with 1 tell the developer that things are fine and the code is just providing us information.
  • 2xx: Success – Status codes that begin with 2 tell the developer that something has been accepted, received or understood.
  • 3xx: Redirection – Status codes that begin with 3 tell the developer that further action needs to be taken before the request can be completed
  • 4xx: Client Error – Status codes that begin with 4 tell the developer/user that the request is written incorrectly or that the request cannot be fulfilled.
  • 5xx: Server Error – Status codes that begin with 5 tell the developer/user that the server failed to do something, despite the request being a valid one.

HTTP Methods

  • GET – This retrieves information from a server based on the given URI. This should only retrieve data and have no effect on the data stored within the server
  • HEAD – This is GET but without the entity-body.
  • POST – Used when the client wants to send data to the server.
  • PUT – Requests the server stores something included in the HTTP request. The server stores the data and sends a response back tot he client saying the data has been created.
  • DELETE – Requests the server deletes a file at a specific location based on the URL. The server will delete the file and will then send a response to confirm deletion.
  • CONNECT – Used to establish a connection to a server. When the client does this, they receive a response based on the current configuration.
  • TRACE – This echos the contents of the HTTP request back to the requester. This is used for debugging purposes during development. When the server processes the request, it will send a message in response to the request.

Conclusion-ish

Ok so HTTP requests are not that complex. It’s just a computer system of interaction where the process of information is exact singular. Make a request, close communication. Create a response, close communication.

The part I’m really struggling with is how the HTTP requests are sent around using ExpressJS. That’s what I’ll focus on tomorrow.

Thank you for reading. Leave a comment below if you have some quality insights I’ve missed here. If you found this helpful, please let me know below as well.

Today I Deployed my First Web Application

For the past few years, I’ve been focused on learning full-stack web development. It turns out that writing a web application is hard. Here’s the result:

My First, Running Blank Web Application

first full stack web application

If you think this web app is just a box that adds to a list, you’re right. It’s ridiculously simple in it’s functionality, but it’s also a fascinating collection of web technologies.

This application serves a page from a hosting service (Heroku) takes data from a user (via web browser), writes it to a database on a separate services (hosted with mLab), reads from the database the updated list of forests and finally serves a page with the updated data to the user.

This is a big day for my career as a builder of web application. A full-stack developer is a person who can make programs on every level from the JavaScript that runs the server to the css which styles the page.

There is a lot I will never understand. Node and V8 go from C++ to JavaScript which I don’t understand. The C++ that runs the database is all written by the MongoDB community. The NPM list of packages is a giant hairball that I don’t understand. Just ‘”npm install” and pray’.

But aside from being in the dark on all of that stuff, I now have a little experience building a full-stack web application.

I’ve open sourced my work so it’s free for anyone to copy this code and use it to write their own web application. You can clone the repository via this link:

Express Skeleton Mongoose Handlebar – Blank App

What is Next?

Now it’s time to write more complex applications.

PRAISE ODIN! The Havamal in JavaScript

Here’s a quick little project I made using normal JavaScript, HTML5, and CSS.

Havamal in JavaScript
On GitHub | Live

This was a quick fun project. I copied the text from the University of Pittsburg’s page and used regular expressions to convert it into a JavaScript array.

When I started, that was going to be the extent of the project. Once I committed it to GitHub, I decided it would be cool to display it in a modern way because… it’s weird seeing ancient texts displayed in a modern way.

Thank you:

The University of Pitsburg provided the text of the Havamal which I converted to a JavaScript array.

It’s mobile responsive thanks to the Skeleton framework.

Doc Holiday Soundboard – Vanilla JavaScript and the Skeleton Framework

This evening I completed my Free Code Camp Front-End Library certification wrapping up the projects with a Doc Holiday Soundboard.

Doc Holiday Soundboard

The project was built using vanilla JavaScript and a mobile responsive CSS library called Skeleton.

Though these projects request that we use complex software like React and Redux, I couldn’t bring myself to do that for this project. This project was too simple to run those huge front-end libraries.

If you’re interested in learning more about the project and the process I went through to build it, you can find all version history on GitHub.

Thank You

Thank you to DHG for the Skeleton framework.

JavaScript ES6 Spread Operator

This is in response to a FreeCodeCamp curriculum session which teaches spread operators.

I found FCC’s explanation of spread operators (click here) to be a very complex description of a simple concept.

Thank you to Brandon Morrelli’s article which provided a clear description of how spread operators can be used to make it easy to work with arrays.

How the Spread Operator Works

Here is the simple way of understanding how a spread operator works:

var arr1 = ['three', 'four'];

var arr2 = ['one', 'two', ...arr1, 'five', 'six'];

console.log(arr2);
// logs [ 'one', 'two', 'three', 'four', 'five', 'six' ]

Essentially the spread operator allows us to inject arrays into spots where we want only the elements, not the array container.

Here is an example of what happens when we don’t have a spread operator:

var arr1 = ['three', 'four'];

var arr2 = ['one', 'two', arr1, 'five', 'six'];

console.log(arr2);
// logs [ 'one', 'two', [ 'three', 'four' ], 'five', 'six' ]

In the example above, we have a nested array which could be problematic depending on the architecture of your application.

Essentially, this makes it so we can evaluate arrays in place.

ES6: Use the Spread Operator to Evaluate Arrays In-Place

This is the answer that passes the tests in the current version of Free Code Camp:

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
(function() {
  "use strict";
  arr2 = [...arr1];
})();
console.log(arr2);

 

Matt Mullenweg on ChangeLog Podcast

Download the Matt Mullenweg podcast and learn more about the ChangeLog podcast.

Special Notes and Quotes from the Podcast

WordPress is a software which is reported to power about 25% of the internet (it appears to be 30.8% now). That’s an amazing accomplishment for a group of people.

“I think, if anything, it shows how much is left to do. Billions of people only have access to publish online through proprietary networks (Twitter, Facebook, etc…). People deserve their own home on the web. They deserve a slice of it which is just there. A place that isn’t tracked or has advertising or anything like that. Essentially, just like their home.” – Matt Mullenweg (paraphrased from 27min 27sec)

What is the business mode of Automatic and what is the business model of WordPress?

WordPress:

  • Doesn’t need a business model
  • No costs – No need for revenue
  • Open Source model staffed by volunteers and those paid by other organizations

Automattic:

  • For profit company with investors and more than 400 employees
  • We find a model in which we benefit the community and the community benefits us
  • We stay away from monetizing things which should be free
  • Jetpack and WordPress.com are supported by way less than 5% of the users
  • Automattic is allowed to invests 150-200 million dollars into WordPress.org

 

Not Locking in Users

“With WordPress.org, you can download and use your data elsewhere. With Facebook, you can download your data, but what do you do with it after that?” – Matt Mullenweg

Product Development and Responsibility Diversificiation

40 min 0 sec – They discuss how to motivate people in environments where all the workers are volunteers. In technology businesses, most engineers have the ability to work wherever they want. Therefore delegating responsibility and enjoyable meeting planning is critical to keeping people motivated to do their best work.

The next 4-10 minutes of the podcast discusses a nuanced difficulty in team leading and product development in large, remote teams. I’ll paraphrase what I’m hearing:

If we diversify responsibility or hierarchy across a group of people, the leaders involved in that organization will have more empathy for team members and team members will have more empathy for their leaders. Why? Because many people in the organization have had the experience of being in the position of the other person.

Moving on to a Developer Centric Conversation – Calypso

At 46:45 they start to discuss Calypso which is essentially the transfer of WordPress to 100% JavaScript and API communications. This is the section of the podcast for developers and those interested in getting involved in the WordPress codebase.

Matt Mullenweg on the Future of JavaScript

I’m happily betting on JavaScript. It’s hard to imagine a [future] world [without JavaScript]. Browsers evolved from being about documents to being about applications. JavaScript is the lingua franca of those applications.

Addressing Anxeity for Developers

Matt suggests listening to State of the Word 2015. I’ve embedded that speech in the link below, a 1hr and 40min talk that Matt gives. Here it is:


1hr 6min 30sec – If you’re building a plugin today, I believe you should turn your interface into JavaScript and embed it in WP-admin….

 

In the podcast, Matt says “[If you read one thing based on this interview, read]… an essay by Orson Wells, called politics and the English language.”

It’s likely that Matt made a mistake by saying Orson Wells, where he should have said, George Orwell. I’ve saved that old essay to this server and you can read the text via this link.