Today I Learned

A Hashrocket project

Include Some Stats In Your Git Log

A simple git log command is going to give you a concise set of information for each commit. Usually it is enough info. When it’s not, git log can provide additional information with the right flags. To include overall and per-file stats on the number of insertions and deletions, use the --stat flag.

$ git log --stat
commit 66e67741a1cd6857a4467d1453c9f17ef5849f20
Author: jbranchaud <jbranchaud@gmail.com>
Date:   Mon Nov 13 21:24:41 2017 -0600

    Add Focus The URL Bar as an internet til

 README.md                     |  3 ++-
 internet/focus-the-url-bar.md | 10 ++++++++++
 2 files changed, 12 insertions(+), 1 deletion(-)

commit 9241e3919ef1e4f68b71a1491d368ae6361084aa
Author: jbranchaud <jbranchaud@gmail.com>
Date:   Sat Nov 11 11:41:40 2017 -0600

    Add Freeze An Object, Sorta as a javascript til

 README.md                            |  3 ++-
 javascript/freeze-an-object-sorta.md | 44 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)

...

See man git-log for more details.

Stop #bash script on error #linux #zsh

If you are writing a procedural bash script, you may want to stop execution if one of the steps errored out.

You can write error handling for each step, but that can get quite verbose and make your script hard to read, or you might even miss something.

Fortunately bash provides another option:

set -e

Simply place the above code at the top of your script and bash should halt the script in case any of them returns a non-true exit code.

Caveats: this will not work in all cases, for example it does not work for short circuited commands using &&/||.

If you want it to work when one of your operations in a pipe fails you will need to add the pipefail flag (not supported on some systems set -o | grep pipefail to check your system):

set -e -o pipefail

If you have a script that always returns a non true return code and that’s fine you can override set -e for that command with:

set +e
your_command_goes_here
set -e

At this point I consider it a best practice to include this statement in every script I write.

Partial post body matching with webmock

When using webmock to stub out a post, you can specify that the post has a specific body. When dealing with web apis, that body is json and you want to compare the body to a ruby hash, from the webmock README, that looks like this:

stub_request(:post, "www.example.com").
  with(body: {a: '1', b: 'five'})

In the above example, the whole json body has to be represented in the hash. Webmock provides a way to just examine a portion of the json/hash with the hash_including method. This is not the rspec hash_including this is a webmock specific function using the WebMock::Matchers::HashIncludingMatcher class.

stub_request(:post, "www.example.com").
  with(body: hash_including({a: '1'}))

The rest of keyword arguments 🍕

Sometimes you pass some extra keyword arguments to a method that doesn’t handle them and you get the error ArgumentError: unknown keywords: ....

You can just use ** as the last argument to ignore the rest of the keyword arguments:

def make_pizza(cheese:, sauce:, **)
  puts "Making pizza with #{cheese} cheese and #{sauce} sauce"
end

make_pizza(cheese: 'muzzarella', sauce: 'tomato', chocolate: 'white', syrup: 'mapple')

=> Making pizza with muzzarella cheese and tomato sauce

You can also give it a name to group them:

def make_pizza(cheese:, sauce:, **rest)
  puts "Making pizza with #{cheese} cheese and #{sauce} sauce"
  rest.each {|k, v| puts "#{v.capitalize} #{k} is not good for you"}
end

make_pizza(cheese: 'muzzarella', sauce: 'tomato', chocolate: 'white', syrup: 'mapple')

=> Making pizza with muzzarella cheese and tomato sauce
=> White chocolate is not good for you
=> Mapple syrup is not good for you

Toggle Mirror Display (OSX)

When using a separate display like a projector, I often switch between screen mirroring (my screen matches the secondary display screen) and not mirroring. Especially during a presentation that uses both slides and live-coding in the terminal.

Instead of navigating through ‘System Preferences’ > ‘Displays’ > ‘Arrangement’, and checking or unchecking the ‘Mirror Displays’ checkbox, I can toggle between the two with ⌘ + F1.

List filenames of multiple filetypes in project

Ag (aka The Silver Searcher) is an amazing piece of software. It allows you to define file types (like Ack) and comes prepackeged with some file types.

Using this feature you can list all files of a specific type in your project. For example say we want to list all Ruby and JavaScript files:

ag --ruby --js -l

Ag has the added benefit over Ack, that it ignores gitignored files, so you only get the files that matter (and not stuff from node_modules etc).

To see what filetypes Ag supports:

ag --list-file-types

The list is pretty extensive! Unlike Ack however, there is currently no way to add new file types or extend the list.

Using ngrok to evaluate webhhooks in a dev env

A webhook, an http request to a server initiated by an outside service, is difficult to test. The outside service must have a valid url to make the request with, but your development server generally runs on the unreachable localhost.

The Ngrok product page describes ngrok like this:

It connects to the ngrok cloud service which accepts traffic on a public address and relays that traffic through to the ngrok process running on your machine and then on to the local address you specified.

If I have a local dev server on port 3000 I run ngrok like so:

> ngrok http 3000
Forwarding   http://92832de0.ngrok.io -> localhost:80

Then, configure the outside service to point the webhook at the ngrok.io address provided by the ngrok tool. Now, your local server will receive http requests from the outside service and you can evaluate those requests effectively.

Focus The URL Bar

There are a lot of things you can do in the browser without having to reach for the mouse. Bringing the URL bar into focus is one of those things.

Hit Cmd+L in any modern browser (I’ve tried Chrome, Firefox, and Safari) and the URL bar will be brought into focus. From there, you can quickly change the URL of the current tab and your fingers never left the keyboard.

h/t Jake Worth

Alternate names in destructuring assignment

Want to use destructuring assignment, but don’t like the names of the variables as they exist in the object?

If you have data like this:

const optimus = { name: 'Optimus', type: 'Semi-Truck' };
const bumblebee = { name: 'Bumblebee', type: 'Small Car' };

Instead of creating customized variables like this:

const { name, type } = bumblebee;
const bumblebeeName = name;
const bumblebeeType = type;

You can express this type of destructuring in one line like:

const { name: optimusName, type: optimusType } = optimus;

Freeze An Object, Sorta

You can freeze a JavaScript object using Object.freeze which will help enforce some immutability practices. Don’t be fooled though, you can still modify arrays and objects in the frozen object.

Here is what the docs have to say:

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed, it also prevents the prototype from being changed.

And here is Object.freeze in action:

> const things = {one: "two", hello: "world", cats: ["Von Neumann", "Sosa"]}
undefined
> Object.freeze(things)
{one: "two", hello: "world", cats: Array(2)}

> things.one = "three"
"three"
> things.dogs = []
[]
> delete things.hello
false

> things
{one: "two", hello: "world", cats: Array(2)}

> things.cats.push("Sneaky")
3

> things
{one: "two", hello: "world", cats: Array(3)}

See the MDN Docs for more details.

h/t Jake Worth

Parameterized SCSS Mixins

A mixin can be made to be much more versatile by parameterizing it. If you need variations of a block of CSS, then move the parts that vary out into parameters to the mixin.

@mixin navigation($background-color, $color, $link-color) {
  nav {
    display: flex;
    justify-content: space-around;
    background-color: $background-color;
    color: $color;

    ul {
      list-style: none;

      li a {
        text-decoration: none;
        color: $link-color;
      }
    }
  }
}

div.base-nav {
  @include navgation(#fff, #444, #222);
}

div.admin-nav {
  @include navgation(#000, #fff, #ddd);
}

The mixin can now easily be used to customize different segments of your app’s styling.

Slow Down, Sinatra

Right now we’re using Sinatra to mock an API. An important consideration for our frontend experience: what happens when the API takes a long time to respond? How do the pages look when they are waiting on a slow, or absent, server?

Sinatra’s support of before blocks allow us to gauge this:

before do
  sleep(3)
end

get 'some/endpoint' do
  200
end

get 'some/other/endpoint' do
  404
end

With this block, every mocked endpoint will wait three seconds before responding, giving us plenty of time to consider what, in development, would otherwise be an instantaneous delay.

Remove namespaces for easier Xpath queries

Xpath can get strange when namespaces are involved

> doc = Nokogiri::XML(<<-XML)
  <a xmlns='http://www.example.com/xhtml'>
    <b>
      <c></c>
    </b>
  </a>
  XML
> doc.xpath("/a")
[] # returns empty array
> doc.xpath("/*[name()='a']")
# returns the first node

The [name()='a'] isn’t really clear and will become less clear as the query looks for elements deeper in the document. When the namespace doesn’t provide any value, for instance by helping to avoid collisions, or helping to validate the given xml document, then removing the namespace is entirely acceptable.

In Nokogiri you can remove namespaces from the document with, remove_namespaces!.

> doc.remove_namespaces!
> doc.xpath('/a')
[<Node a>]

Now traversing the document with xpath will be significantly more straightforward.

Dry Up SCSS With Mixins

If you have a similar chunk of styling that is being duplicated across your CSS, you’d probably like to dry it up to reduce the pain of maintaining it. Mixins provide one way of dealing with this problem.

First, declare a named mixin of the styles that you are trying to dry up.

@mixin navigation {
  nav {
    display: flex;
    justify-content: space-around;

    ul {
      list-style: none;

      li a {
        text-decoration: none;
      }
    }
  }
}

Then, this mixin can be included wherever it is needed.

div.base-nav {
  @include navigation;
  background-color: #fff;
  color: #444;

  nav ul {
    li a:hover {
      color: #222;
    }
  }
}

div.admin-nav {
  @include navigation;
  background-color: #000;
  color: #fff;

  nav ul {
    li a:hover {
      color: #ddd;
    }
  }
}

Any subsequent changes to the core navigation styling only need to be made in one place, the mixin.

source

h/t Dorian Karter

Iterating over objects in Lodash

Many of the Lodash collection functions iterate over either an object or an array. Somewhat unintuitively for me, when iterating over objects the first argument of the iteratee function is a value and the second argument is the key.

The documentation for Lodash lists the arguments for the iteratee in the description for each function. For collection functions that generally looks like this

The iteratee is invoked with three arguments:(value, index|key, collection).

By searching through the documentation for index|key you can find all the functions for which this is true.

Using a Lodash function that can return iterate over an object looks like this:

const result = _.map({a: 1, b: 2}, function(value, key) {
  return value + key;
});

// result is now ["a1", "b2"]

H/T Ryan Messner

Reloading shell history in zsh

When you start a shell your history list is populated from your .zsh_history file. Depending on options that you have set, when you close a shell you write your history list to that same history file. Until you close your or open new shells that history is self contained and not accessible from another shell.

There is a built-in zsh command to both write and read history from the .zsh_history file. fc -W will write to the history file. fc -R will read from the history file.

Upgrading From An Older Version On Mac

To upgrade from an older version on Mac, there are a couple manual steps that you need to take. For starters, download the latest installer for Mac from Go Lang Downloads.

While this is downloading, you’ll need to delete the older version of Go that is installed on your machine.

First, remove the existing Go installation directory:

$ sudo rm -rf /usr/local/go

Second, clean up the Go bin directory from your PATH environment variable:

$ sudo rm /etc/paths.d/go

Now, you can double click on the downloaded installer dmg and follow the prompt instructions.

When its all said and done, check go version from the command line to see that you are now working with the latest.

Ch-ch-ch-ch-changes

For everyfile in vim, vim remembers the position of the changes that have occurred. These change positions are stored in the changes list for each file and can be used for intrafile navigation with the two commands g, and g;.

This is really handy if you switch to a large file and need to quickly flip through the most recently changed sections of that file.

View the entire list of changes for a file with the command :changes.

`Object.entries` helps you iterate over objects

You may find yourself with an object with lots of entries that you need to transform into an array of extracted information. For examples sake lets say:

  const things = {
    a: 1,
    b: 2
  }

And we need to turn that into and array [2, 3].

We can use Object.entries to turn the object into an array of key/value tuples.

const arr = Object.entries(things)
// arr === [["a", 1], ["b", 2]]

Then we can iterate over that array with map:

const mappedArr = arr.map((tuple) => {
  const [key, value] = tuple;
  return value + 1;
});
// mappedArr === [2, 3]

Object.entries is an ES7 proposal implemented in Chrome/Firefox/Edge and polyfilled with CoreJS, the polyfill library used by Babel.

Chrome Dev Tools Selection Variable

Highlight a few HTML elements in the Chrome Developer Tools Elements inspector, and you’ll have a traversable history. The selected element is stored in a variable called $0. We can manipulate it like so:

> $0.click();

Try this when the selected element is hidden or difficult to click. There are four more variables representing your most recently selected elements: $1, $2, $3, and $4.

h/t Josh Branchaud

Accessing Env Vars In create-react-app

Environment-specific configurations are an important part of most applications. You can access environment variables in your create-react-app code using process.env.

There are a couple built-in environment variables, such as NODE_ENV. Anything custom that you want to provide must be prepended with REACT_APP_. If it isn’t, that environment variable will be ignored with no warning.

The following line of code

const base_api_url = process.env.REACT_APP_BASE_API_URL;

will have access to whatever that value is in the environment when the server is started or the app is built.

Set that value inline like so:

REACT_APP_BASE_API_URL="https://api.my_app.com" yarn start

source

Compare Form Values with Yup

We’ve been using yup to validate a JavaScript form, and found ourselves facing a common problem when a user signs up for a service:

How do we ensure a user’s email matches their email confirmation?

yup’s test function helped us find a solution. It’s documented like this:

mixed.test(name: string, message: string, test: function)

test takes a name, a message to show on failure, and a function that returns a boolean. We paired this with the email we get from our parent.

var schema = yup.object().shape({
  email: yup
    .string(),
  emailConfirmation: yup
    .string()
    .test('match', 
      'emails do not match', 
       function(emailConfirmation) { 
         return emailConfirmation === this.parent.email; 
       }),
}),

glamorous composition for inline styling

glamorous is a library to help style components from the component itself rather than from a css stylesheet. You create a component with style in the form of a javascript object.

require glam import 'glamorours';

const InfoSpan = glam.span({
  backgroundColor: 'none',
  width: '20%',
  margin: '0 1rem',
  padding: '0 1rem',
  display: 'inline-block',
  boxSizing: 'borderBox'
});

Later when rendering, you can use this as if it were a component.

render() {
  return (
    <div>
      <InfoSpan>
        Some Important Information
      </InfoSpan>
    </div>
  );
}

You can also compose additional glamorous components by re-using previously declared glamorous components.

const LeftSpan = glamorous(InfoSpan, {
  textAlign: 'right'
});

const RedArticle = glamorous(Article, {
  textAlign: 'left'
});

Vim Projectionist Default File of Type

When setting up vim-projectionist, we can add a directory and filetype like this:

{
  "src/components/*.js": {
    "command": "component"
  }
}

With this in place, :Ecomponent will tab-complete to any JavaScript file in src/components, and :Ecomponent navbar will jump straight to the navbar.js component.

Let’s add a second key that includes a hard-coded file name.

{
"src/components/*.js": {
    "command": "component"
  },
  "src/components/App.js": { "type": "component" }
}

This pair tells vim-projectionist to jump to App.js if no argument is provided to :Ecomponent.

Replace App.js with your root component, and you have a shortcut to the top of your component hierarchy.

Catchall in a React Router Switch

Today we built a 404 page for a React app using React Router, via a Switch statement with no specified path. Like a default clause, it catches if none of the other routes match:

<Switch>
  <Route path="/about" component={About}/>
  <Route component={NoMatch}/>
</Switch>

On any other path besides /about, we’ll render our NoMatch component.

Casting graphql types with inline fragments

Graphql works with a type system. You ask for fruit and it returns fruit, but that fruit could be a pear or an orange.

(contrived example apologies)

interface Fruit {
  seedless: Boolean
}

type Pear implements Fruit {
  color: String
}

type Apple implements Fruit {
  size: Int
}

So when you ask for fruit, and you want the size of the apple, you have to let graphql know that you want an Apple and are expecting an Apple and while I’m thinking about this as casting the graphql docs call it inline fragments.

  query {
    fruit {
      seedless
      ... on Pear {
        color
      }
      ... on Apple {
        size
      }
    }
  }

The ... is a syntactic element not a writing convention.

Animating polygon must have same number of points

You can show an SVG polygon changing shape with SVG’s animate tag.

<polygon points="100,100 0,100 0,0">
  <animate
    to="50,50 0,50 0,0"
    from="100,100 0,100 0,0"
    dur="10s"
    attributeName="points"
  />
</polygon>

However, you can not animate a shape change to a different number of points. For instance if you have three points in the to attribute and four points in the from attribute, then nothing will happen.

Recently, I wanted to animate a change from a 4 pointed polygon to a 5 pointed polygon. In this case, I included an extra point in the 4 pointed polygon that was a duplicate of an existing point and right next to that same duplicated point. When changing shape to a 5 pointed polygon, the previously duplicated point moved out from that spot to its new spot and the polygon adjusted accordingly and pleasingly.

Custom Browser with Create React App

Sometimes Google Chrome isn’t your default browser for surfing the internet, but it is your default browser during development. With create-react-app you can specify an alternate browser to automatically open (or no browser at all), to avoid opening the wrong development browser all the time.

Just pre-pend the browser to the start script:

{
  "name": "custom-browser",
  "version": "0.1.0",
  ...
  
  "scripts": {
    "start": "BROWSER='Google Chrome' react-scripts start",
    ...
  }
}

Search Github Faster with Shortcuts

Last year, I wrote about Github repository shortcuts for code, issues, and pull requests.

Now Github has a projects tab on each repository. Ever the completist, here’s the shortcut for that tab: gb. Typing this on a Github repo’s page loads the projects tab.

Researching this led me to an even better shortcut, s. This is site-wide and it focuses the Github search bar.

Here’s the impressive full list of Github hotkeys.

Elixir Maps With String/Colon Keys Become Atoms

While running the Elixir 1.6 formatter against Today I Learned, this change caught my eye. The formatter changes maps like this:

%{ "short_name": "TIL" }

To this:

%{ short_name: "TIL" }

This change makes sense because Elixir automatically coerces strings keys in a map, when followed by colons:

iex(1)> %{"foo": "bar"}
%{foo: "bar"}

And so, the conversion is implied. Elixir 1.6’s formatter forces us to be explicit and skip the conversion.

String Interpolation With Template Literals

ES6 adds support for template literals. Template literals make it much easier to compose strings of content — string interpolation. They allow for single and double quotes without having to fuss with escaping. Embedded expressions are also supported which means you can avoid awkward-to-type string concatenation with the + operator.

Here is an example:

> let movie = 'it'
undefined
> `What's up, I just saw "${movie.toUpperCase()}".`
"What's up, I just saw "IT"."

Proxy To An API Server In Development With CRA

create-react-app is a great way to bootstrap a React project, especially if you are building a single-page app. When building an SPA, you more likely than not will have a backend API that you interact with.

You can set up your React app to interact with that backend API server in development using the proxy configuration in package.json.

// package.json
  ...
  "proxy": "http://localhost:4000",
}

This will allow you to keep your API calls nice and clean.

fetch("/api/session", ...

No need to manage some sort of host URL environment variable.

Additionally, this will remove an CORS issues because the webpackDevServer will be proxying any paths that it doesn’t recognize to the host and port that you’ve specified.

See the create-react-app docs for more details.

Split The Current Window

Generally when I want to open up a buffer in a window split, I use :sp or :vsp and type out the filename. It may be a bit more convenient to use window commands to create the splits.

To open a horizontal split:

Ctrl-w s

To open a vertical split:

Ctrl-w v

With the split made, you can use Ctrl-o/Ctrl-i, BufExplorer, or whatever way you like to navigate between buffers.

h/t Ryan Messner

Turn Off HTML5 Form Validations

HTML5 added a variety of input types such as date, email, and tel (telephone number). These make entering certain kinds of information easier by providing tools such as a datepickers, range sliders, and optimized keyboards on mobile devices.

These input types also introduce custom validations on some browsers, which are useful, but can potentially clash with your application’s look and feel.

To keep the input type, but disable the validations, add novalidate to your form tag:

<form novalidate />

h/t Dillon Hafer

docs

Make console.log stand out with custom css style

I know your browser console is full of messages because you are debugging something, and that creates a lot of noise. Now you are adding a new console.log, and you need it to stand out above the rest.

Maybe you are like facebook and just want to warn your users from pasting in code in the browser in social engineering attacks.

facebook

To style a console.log message use the %c interpolation and pass it a css style. e.g.

console.log('%c%s', 'color:red;font-size:5em', alert)

In the example above %s means inerpolate the object into the output string.

preview

Compatibility: tested to work on Firefox, Chrome, and Safari.

h/t Dillon Hafer

Storing recurring schedules in #Rails + #Postgres

If you have a scheduling component to your Rails application you may need to store the day of week and time of day in the database.

One way to store the day of week is to use an integer column with a check constraint that will check that the value is between 0 and 6.

create table schedules (
  id serial primary key,
  day_of_week integer not null check(day_of_week in (0,1,2,3,4,5,6)),
  beg_time time not null,
  end_time time not null
);

Then when you read it back from the database and need to convert it back to day name you can use Date::DAYNAMES. e.g.:

[2] pry(main)> require 'date'
=> true
[3] pry(main)> Date::DAYNAMES
=> ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
[4] pry(main)> Date::DAYNAMES[0]
=> "Sunday"
[5] pry(main)>

If you need to store time of day as entered (in a time without timezone column - as specified above) check out the wonderful Tod gem by Jack Christensen

Checking that an association is loaded

Ecto will NOT load associations automatically, that is something that you must do explicitly and sometimes you might expect an association to be loaded but because of the code path travelled, it is not.

You can check to see if an association is loaded with Ecto.assoc_loaded?

case Ecto.assoc_loaded?(post.channel) do
  true -> IO.puts('yep its loaded')
  false -> IO.puts('you do not have the data')
end

Ruby Binding Class

Ruby’s Binding class allows you to access classes, variables, and methods outside of the current scope.

class Foo
    def bar
        my_var = 20
        binding()
    end
end

Normally, if you made reference to my_var outside of that method, you’d get an error. Binding objects allow you to do this:

my_foo = Foo.new

foo_bar = my_foo.bar
puts foo_bar.eval('my_var')

# 20

Legacy Refs vs Ref Callbacks

Reactjs provides a way to get references to dom elements that react is rendering through jsx. Previously, it was through what are now legacy refs:

componentWillUpdate() {
  this.refs.thing.tagName == "div";
}

render() {
  return (
    <div ref="thing"/>
  );
}

Where you can assign an element an identifier and react would keep a refs hash up to date with references to the dom for that element.

The react docs say this about the previous system.

We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases.

The new system uses callbacks

render() {
  return (
    <div ref={(div) => { console.log('tag name:', div.tagName); }} />
  );
}

This callback is called when the component mounts with a reference to the dom element as an argument. Importantly, when the component unmounts the callback is called again but this time with null as an argument.