Reason #244 to Hate Javascript

Generate an RFC 4122 compliant UUID: Ruby

require 'securerandom' # at worst, if you're using Rails you won't have to write this

Generate an RFC 4122 compliant UUID: Javascript. It’s not actually apart of the language itself or a standard lib equivalent. Instead, you need to decide on which of about a half dozen npm packages you want to use. Or you can read through this stupidly long Stack Overflow post.

Let’s say, you’re like me and you settle on broofa’s despite quickly reading through a few different comments explaining what some of the problems with that approach might be. His was by far the most readable. Anyway, you get:

const uuid() = function() {
  // stolen from:
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r&0x3 | 0x8);
    return v.toString(16);

This sucks, I don’t want to be responsible for generating UUIDs. Or making sure they adhere to the RFC. (Or even understanding it.) Or making sure they’re performant. Or make my team read that code. I want my language to handle stuff like that 😡

Reason #137 to Hate Javascript

Load all files in folder and sub-folders: Ruby

Dir.glob(File.join(Rails.root, 'folder/of_interest/', '*.rb')).each do |helper_file|
  require helper_file

Load all files in folder and sub-folders: Javascript

const webpack = require("webpack");
const fs = require("fs");

let camelize = function(string) {
  let almost = string.replace(/(\_\w)/g, matches => matches[1].toUpperCase())

  return almost[0].toUpperCase() + almost.slice(1);

let filename = (path) => (path.split("/").pop().split(".").slice(0, -1).join(""));

let allFilesIn = function(dir) {
  var results = [];

  fs.readdirSync(dir).forEach(function(file) {
      let path = dir + '/' + file;
      let stat = fs.statSync(path);

      if(stat && stat.isDirectory()) {
        results = results.concat(allFilesIn(path))
      else {

  return results;

let components = allFilesIn(__dirname + "/folder/of_interest/").
  map((path) => {
    return { test: require.resolve(path), loader: `expose-loader?${camelize(filename(path))}` }

let config = {
  entry: {
    application: __dirname + "/app/assets/javascripts/application_entry.js"

  output: {
    path: __dirname + "/app/assets/javascripts"

  module: {
    loaders: components.concat([
        test: /\.(js|jsx)$/,
        include: __dirname + "/folder/of_interest/",
        loader: "babel",
        query: {
          presets: ["es2015", "react", "stage-2"]

module.exports = config;

But wait, theres more–we still need to require in the entry file:

  (context) => { context.keys().map(context) }
)(require.context("./folder/of_interest", true, /\.(js|jsx)$/));

You might notice, we’re exposing modules in /folder/of_interest/ globally and that’s part of the complexity here. True. We’re doing that to work with the react_ujs library that’s a part of the react-rails gem.

What?! 😳 In my code? Yes! 😁

Emoji’s might be one of the coolest inventions to hit cell phones. Just behind the Internet. And texting itself. They’re capable of adding so much meaning, but probably most importantly, they’re fun to use.

And clearly, people tend to agree. Most people litter their texts with them. In fact, I can tell when my wife’s displeased with me just by the decreased frequency of smiley faces in her texts. Facebook recently added them. Hundreds of people took the time to write an entire book using nothing else. GitHub even took the time to make them a part of the software development process.

But you know where I haven’t seen them? Comments. And why not? I’d be willing to guess most people (certainly millennials and younger) use them in their text message conversations all. the. time. To convey that extra level of meaning. Because “😂😂😂” shows your amusement better than “lol”. And “👌” is quicker cooler than “ok”.

What are comments if not quick text messages to your future reader? By adding emojis to our comments we can convey not only the technical details of why we wrote the code we did, but also how we felt about the code when we wrote it. And I’d argue that can be valuable to your future reader, be that yourself or someone else.

Not to mention, it can make the drudgery of documenting code more bearable. You know…slightly…

Let’s look at some examples from codebases I’m juggling at work right now:

Utterly Exasperated

class Compass::History::Loan < Compass::Connection
  self.table_name = "KWHLOAN"

  # i'm not _entirely_ sure of the structure here, but it looks to me like a
  # KWHLOAN can be associated with exactly one KWHBASE row when both the HSEQ
  # and HDATE columns are equal. in other words:
  #                                             KWHBASE.HSEQ = KWHLOAN.HSEQ;
  # we're replicating that as a has_one association by making the HDATE column
  # the primary key and adding conditions for the HSEQ portion. that's a
  # little misleading because technically there is no primary/foreign key
  # associating these two tables 😪
  has_one :past_payment, ->(loan) {
    where(hseq: loan.hseq)
  }, class_name: "Compass::History::Base", foreign_key: :hdate,
                                           primary_key: :hdate

I think adding this “exasperated sigh” emoji helps draw attention to our comment. It adds my emotions at the time of writing. I was exasperated with this code. I felt like my hands were tied. I needed an association the legacy database didn’t really support, and so we’re stuck doing something kinda gross. The words convey the technical details of why. The emoji? That cues my future reader into how I felt about this code. All with a simple keystroke.

An Inside Joke, Just for Fun

def setup_organization # for use in testing when we need groups
  groups = {
    'married' => ['', ''],
    'tough' => ['', '', ''],
    'large_and_semi_muscular' => [''] # 😂

  # some FactoryGirl shenanigans...

Perhaps, not the most necessary usage. But sometimes it’s important to have fun with your code and your future reader. Especially, in test code, which isn’t always the most fun to read or write. At least now the reader knows there’s an inside joke here, and, if curious enough, could look it up.

Who Designed This?!? 😡

(See what I did there? 😂 And again.)

def should_alert?
  # luckily, the type and user.alerts_type arguments don't match 😑
  !vulnerabilities.empty? &&
    (user.alerts_type == "all" || case type
                                    when "new"
                                      user.alerts_type == "new"
                                    when "updated"
                                      user.alerts_type == "updates"

This defines a quick helper method that lets us know if we should alert a user based on his alert settings and the type of alert we’re processing. But, of course, type and user.alerts_type don’t use the same verbiage so we have this complicated case checking. Me being me, I added some sarcastic text explaining this, and my personal “wtf?!” face emoji.

Normal prose has both voice and style. I think style comes pretty naturally when writing code. Whether good or bad, most developers have style in their code. How they indent things, when they comment, what constructs they use to do X vs Y, those are all part of a coder’s style. But I don’t think voice comes through as evidently. Emoji’s add the voice. They make your code more personal, and ultimately more enjoyable to read.

If you’re sold, here is the emoji plugin I use with Sublime Text 3 which makes it super easy to search for and insert emojis. Here’s hoping we see more 😁’s and 💯’s than 😑’s in our comments!

Sublime Settings

Mostly, this is for my own personal reference, but since I was forced to deal with it when I really wanted to write about something else, I decided to document. So, here’s my current Sublime Text 3 settings.

Obviously, you should be using Package Control, so I won’t waste any time on that.

The next thing you should use is the Material theme. The README provides details on all the configurable options, but for simplicity here’s my complete personal settings that I have found to look good. Note: some settings are related to the Material theme and others not:

  "always_show_minimap_viewport": true,
  "auto_complete_commit_on_tab": true,
  "bold_folder_labels": true,
  "centurion_folder_icons": true,
  "color_scheme": "Packages/Material Theme/schemes/Material-Theme-Darker.tmTheme",
  "contrasted_quick_panel": true,
  "contrasted_sidebar": true,
  "contrasted_tabs": true,
  "find_selected_text": true,
  "font_size": 11.0,
  "icon_file_type_enable": true,
  "line_padding_bottom": 1,
  "line_padding_top": 1,
  "overlay_scroll_bars": "enabled",
  "preview_on_click": false,
  "shift_tab_unindent": true,
  "soda_folder_icons": true,
  "tab_size": 2,
  "tabs_medium": true,
  "theme": "Material-Theme-Darker.sublime-theme",
  "translate_tabs_to_spaces": true

What slowed me down tonight was getting something reasonable for editing Markdown files working. I wasn’t a huge fan of how Material worked with Markdown. So I tired MarkdownEditing, but wasn’t really a huge fan.

But, I did find Markdown Extended, which looked pretty good! However, it works best with the Monokai Extended color scheme. And I didn’t want to stop using Material. So, what I did was download both Markdown Extended and Monokai Extended, but only use the Monokai Extended color scheme in my .md files.

To do this, first, install the packages. Then open a .md file. Navigate to Preferences > Settings - More > Syntax Specific - User and add the following:

  "color_scheme": "Packages/Monokai Extended/Monokai Extended.tmTheme",
  "spell_check": true

Monokai Extended blends almost perfectly with Material, and now Sublime Text will seamlessly switch your color schemes depending on the open file.

With that, you should be all set to use Sublime Text for all of your development work, as well writing for that Jekyll blog you’ve always meant to work on!

On the Name

I’ve always thought “Gray Matter” would be an awesome name for my blog. My first name is Gray. Gray matter is a substance found in the brain which invokes a certain imagery, and I figured my blog content would air on the intellectual side. And “Gray Matter” taken on it’s own sounds like “matter published by Gray”. Perfect, right?!

But then “Breaking Bad” came out before I had a chance to make a name for myself.

When I was dating my wife (a huge “Breaking Bad” fan), at one point I told her about how cool it would be to have a well read blog called “Gray Matter”. To which she responded, “OH! Like ‘Breaking Bad’?!”

. . .

“Umm, no. Not like that all. I had this idea on my own, you know because of my name…”

Which is true. I didn’t watch “Breaking Bad” until sometime after the entirety of the show was available on Netflix, which happened in early 2014. Should have executed better, but to prove I’m not entirely unoriginal here’s some emails I sent to the person who owns the “” domain.

Attempt One

Note the date: 2010. That’s me in high school asking to buy the name, before everyone was watching “Breaking Bad”. I never heard back though.

So I tried again.

Attempt Two

Not my best sales pitch ever, but I didn’t have high hopes. The website, which was just an email address, hadn’t changed in years. I wasn’t even sure the email worked.

Anyway, that’s my “Hello World” post. Welcome to “Gray Matter”.