Corey Ward

Full-stack, freelance designer + web developer building GatsbyJS and Rails websites. I also design and build furniture.

Page 2

Co-dependent Models in Rails

Sometimes you have a one-to-many relationship in your Rails models and you want to allow nested attributes at the time of creation. So you do this:

 Seems like it would work, but does NOT:
class User < ApplicationModel
  has_many :tags
  accepts_nested_attributes_for :tags

class Tag < ApplicationModel
  belongs_to :user

When you try to save a user, though, you run into trouble: ActiveRecord tries to validate autosaved nested records, and those nested records have an implicit required: true validation on the parent model which, in this case, doesn’t have an ID yet.

The fix is simple, but unintuitive: manually specify the inverse_of option on the association. ActiveRecord can create a bidirectional association automatically, but in this particular case, it doesn’t work.

 Redundant, but works
class User < ApplicationModel
  has_many :tags, inverse_of: :user

Continue reading →

Quick Fix: Keyboard Brightness Controls on macOS (external Apple Display)

I recently had an issue where the keyboard controls to adjust monitor brightness weren’t functioning on my Apple Macbook Pro running macOS Sierra. The Displays pane in System Preferences showed no brightness adjustment despite showing the correct monitor visual and name (LED Cinema Display, in my case).

It turns out that Apple uses the USB connection to communicate with these monitors. That connection had, for one reason or another, failed to be initialized or was erroneously terminated. The fix was simple: unplug the USB cable that goes from the monitor to the computer from the USB port on the computer, then reinsert it. No restarting necessary.

After this fix, the Displays pane went back to normal showing the brightness adjustment:

macOS Sierra Displays preference pane showing brightness adjustment

Continue reading →

How to fix TypeError: Nil is not a Symbol or String

If you’re using the form helpers built into Rails (or a library like SimpleForm that’s built on top of them), you might run into a somewhat confusing error:

TypeError: nil is not a symbol nor a string

Usually this will originate from somewhere like value_for_collection which is part of the FormOptionsHelper in ActionView, but grepping the source won’t yield any results for the error string. You might be experiencing this in your own application you’re using a tiny dose of metaprogramming.

That’s because TypeError comes from Ruby. The actual call raising this error is __send__, which is happening in the Ruby internals after a call to send. In the FormOptionsHelper example case above, value is nil, and Rails tries to call item.send(nil) which won’t work.

If you’re encountering this in your own code this should be easy enough to fix: add a nil guard to ensure the value you’re...

Continue reading →

A few terminal shortcuts for Rails devs

Here are a few command-line shortcuts for anybody that uses Ruby or Ruby on Rails on a daily basis:

Abbreviate bundle exec [command]

Replace bundle exec with just be and you no longer have an excuse for running a rake without the dependency-locking prefix.

alias be='bundle exec'

 Example Usage
$ be rake
 equivalent to bundle exec rake

Abbreviate calls to rails …

And use the binstub! This takes advantage of Spring to avoid reloading the app (if it’s in memory), making a call to br c load up a console much faster.

alias br='./bin/rails'

Get the latest Rails version

Anytime I launch a new Rails app I check for the latest stable release. Instead of heading to the browser and checking the weblog or Rubygems everytime, I use this handy shortcut:

gem list -r ^rails$ | tail

This will output something like rails (5.1.1). You can then easily compare against what you’ve got...

Continue reading →

Quick Tip to Clean Up Rails Logs

Every few months I use this command to empty each and every one of my test.log and development.log files in the src folder of my laptop:

find ~/src \
  -maxdepth 6 \
  -type f \
  -mindepth 1 \
  \( -name "test.log" -or -name "development.log" \) \
  -exec truncate -s 0 {} \;

It works by…

  1. Finding files that match the name
  2. Using the truncate command to reduce the size of the file to 0 bytes

Instead of typing it out each time, I’ve created a quick alias in my .bash_profile when my shell loads:

alias truncate_devlogs='find . -maxdepth 6 -type f -mindepth 1 \( -name "test.log" -or -name "development.log" \) -exec truncate -s 0 {} \;'

Then when I remember to do so, or I wrap up work on a project, a quick truncate_devlogs recoups disk space and makes me feel better.

Continue reading →

Make iOS Show CSS :hover Styles Without Any JS

Occasionally I’ll build an interaction that happens entirely in CSS via hover or focus on a non-standard element. Unfortunately, iOS doesn’t apply hover states when you tap on, say, a div. The solution is to get iOS to treat that element like a link by listening for clicks.

One way to do this without changing any other behavior on the page is to add an onclick to the desired element:

<div onclick="void(0)" class="fancy-hover">…</div>

Tapping will now trigger the :hover CSS styles for this element. Tapping away, doesn’t have the desired effect by default. In those cases, you can also add this:

<body onclick="void(0)">…</body>

This assumes you’re not using the onclick attribute because it’s 2017 and there are better ways of registering those click handlers. ;)

View →

Render templates from anywhere in Ruby on Rails

Rails 5 recently shipped, and among many other new features is a new renderer that makes it easy to render fully composed views outside of your controllers.

This comes in handy if you want to attach, say, an HTML receipt to an order confirmation email, or render an HTML template for wkhtmltopdf to convert to PDF.

Previously it was a chore to render views with their full context. You needed to emulate a request and a controller instance, and keep track of the relatively intricate suite of methods and their signatures. The new Rails 5 renderer provides a handful of intuitive interfaces right on the ActionController::Base class that are inherited by your ApplicationController et al.

Here’s an example:

plain_html = ApplicationController.render('users/show')

That’s all that’s needed for a simple view. Helpers that are available in ApplicationController are available to your view...

Continue reading →

Fixing Broken `gem install` from Xcode update

Quick tip: upgrading to Xcode 8.0 on a Mac with existing dev tools installed results in compilation failures due to the build tool license. You need to agree to the new license before proceeding, which requires running with admin privileges.

So if you get something like this:
Error installing during `bundle install`

You can fix it by running the following:

$ sudo gcc

Hit ‘space’ repeatedly to get through the license, then type ‘agree’ and hit enter. You’ll get a generic error about no input files and that’s when you know you’re good to go. Re-run bundle or whatever you were doing previously.

View →

Lightweight Proc Partials in Rails

I recently needed to display some content “cards” from dynamic content interspersed with static content on a Rails-backed website I was building for a client. Essentially, I needed something like this…

<div class="container">
  <div class="person">John Smith</div>
  <div class="person">Bill Nye</div>
  <div class="interstitial">
    <a href="/sign-up">Sign Up Now</a>
  <div class="person">Carl Sagan</div>

…only where the people are filled in from the database. One solution is using CSS ordering instead of source ordering. This can work really well, but it takes additional time and can increase the cognitive overhead for reasoning about the behavior of a piece of code, especially for someone new to the project.

I wanted the source order to reflect the display order, but I didn’t want to repeat myself unnecessarily.

Verbose, and liable to trip me up in the future:


Continue reading →

Typo Forgiveness in Git & Bash

I’m often moving pretty quickly when it comes time to commit work to Git. I have a bit of a workflow down, and I type the same few shortcuts frequently:

$ git st (expands to status)
$ git ks (expands to difftool, which opens Kaleidoscope)
$ git add -A
$ git ci (expands to commit)

Regularly, though, my fingers will transpose the t in Git and the space that follows it: gi tks.

This has become frequent enough that I finally took the time to address it by making the desired action still occur:

$ git config --global alias.tst status
$ git config --global alias.tks difftool
$ git config --global commit

Then, in ~/.bash_profile:

alias gi=git

Now when I make a mistake, Git does what I want and I don’t lose my flow. It’s a small thing, but it’ll improve my day a little bit a dozen times a day.

Mentioned in this post: Kaleidoscope, the (mostly) fantastic diff visualizer...

Continue reading →