Mark Grealish

> cats and wizardry


Forcibly Set Counter Cache Columns to Zero in Rails 5

(Or any other value you like.) So it turns out that counter cache columns are marked as readonly because Rails handles increment/decrement internally through methods such as increment_counter. Rails does not want you to update the counters by hand. It really wants you to leave the integrity of those fields to the framework itself. Every […]

Ghetto Single-Instance Cron jobs on Elastic Beanstalk

Before you read this article, go and read about Elastic Beanstalk’s worker environments. A worker environment is a copy of your application which you configure to handle certain background tasks. In the case of Ruby on Rails, you can configure ActiveJob to interact with the worker tier through the active-elastic-job gem. If a worker tier […]

instasort 4.0.1

One bad programmer habit of mines is that I tend to duck type when there isn’t a strict need. I ask whether the object doesn’t fit conditions, or evaluate it against some rules, at times when I have the ability to check its actual type. I thusly duck typed images in the previous version of […]

Invalid Authenticity Token Errors in Rails 5

Over the last while we had persistent CSRF token issues in our natively-wrapped application. ActionController::InvalidAuthenticityToken The error only appeared to occur under specific circumstances: Open app. Perform any action, then logout. Log back in again. All remote POST/PUT/DELETE requests will fail with token errors. Typical trace: Started POST "/events/147/attendances" for at 2017-09-12 12:17:54 +0000 […]

Only Show Actual Work on a Git Branch

I find this useful at work when I need to review a pull request using git or tig. Who did the actual work on the branch, when? git log --author=[whomever] --first-parent --no-merges tig --author=[whomever] --no-merges --pretty=fuller --first-parent That said, we do need to rebase at some stage. :p

Pretty Stack Overflow-style resource URLs in Rails 5

Stack Overflow uses routes with the format /:id/:title for questions like this one, which I find to be more memorable than simply a terse ID. I’ve decided that I want this for my new project, a rewrite of this blog in Ruby on Rails 5. Small changes to a model and its routes are required […]

Convert PSD to flattened PNG file with Imagemagick

This turned out to be quite useful at work today: for PSD in *.psd; do convert "${PSD}[0]" "${PSD/psd/png}"; done

instasort 4.0

Another year, another version. My growth as a programmer strikes me when I compare previous versions with the latest code. Less code which works better. You may compare the last three versions together on GitHub. #!/usr/bin/env zsh # # Functions # # # Check if Photograph is (Approximately) Square # # While it was originally […]

Avoid N + 1 issues in Ruby on Rails when checking existance

How perfect and clear, hindsight! This was another “oh, duh” moment for me. Stupid means humble means another step closer to enlightenment, so that’s good. In our application a user may favourite content in a manner à la Facebook. When rendering views, the naive way (the Mark way before this post) is to test for […]

Generate all the rotational permutations of a string

This does not generate lexicographic permutations (use Lexicographer for that!); this plucks off one letter from the end and attaches it to the start: rotations = (str) -> Array(str.length).fill(str).map (rotation, index) -> while index-- rotation = rotation[-1..-1] + rotation[0..-2] rotation I liked my solution and wanted to share.

(Simple!) Sass/Scss margin size management

Like, fuck it. After something like three years fucking with this problem, a realization has come upon me that the simplest solutions are the best solutions. The core of my problem was this: I wanted to manage a set of margin and padding sizes from a central point. I want to base sizes all sizes […]

Circular shift Roman letters in CoffeeScript

This Codewars problem annoyed the crap out of me. shift = (letter, amount) -> mod = if /[A-Z]/.test letter then 65 else 97 String.fromCharCode mod + (letter.charCodeAt(0) + amount) % mod % 26 The formula to constrain a number to a range is: (range_start + offset_here) % range_start % range_size

Hell of a week

I couldn’t get my head straight on Tuesday so I went to look at the sea instead.

Self-Referential “has_many :through” Relationships in Rails 5

A self-referential has_many :through relationship is one where a class interacts with itself through a join table. The classic use are followings: I follow another user. Another user follows me. So a Following is a two-way relationship between the User class and itself. There are a bunch of guides for this that are either outdated […]

Kill puma

Grr, rage, annoyance, rabble. kill -9 $(lsof -wni tcp:3000 -t)

Add sub-controller modules to Rails 5 routing concerns

Routing concerns have been a thing since Rails 4, but this morning I ran into a real annoyance: the documentation doesn’t adequately explain how to pass a module, in cases where you use separate sub-controllers. More than that, even-what if I want to pass any other options? Here’s what I came up with, using splats […]

Simple and dumb MOC theme

MOC <3 background = white default current_time = white default bold directory = white default disabled = white default empty_mixer_bar = white default empty_time_bar = white default enabled = white default bold entry = white default entry_title = white default error = white default bold,underline file = white default filled_mixer_bar = white default reverse filled_time_bar […]

Rails 5 join table naming conventions

This is a stupid fucking thing, akin to Googling basic syntax for your language, but here we are. My underling and I wasted 40 minutes today re-figuring this out. Migration: class PluralSingular < ActiveRecord::Migration[5.0] create_join_table :plural, :plural end Model: app/model/foo.rb class Foo < ApplicationRecord has_many :plural_singular has_many :plural, through: :plural_singular end Join model: app/model/plural_singular.rb class […]

What I did on my summer holiday

I finished with one programming job on Friday and I start my next Monday. That means it’s time for some good ol’ retrospection. I used to think I was a special snowflake because I fell into coding, but Stack Overflow says otherwise. I wrote a great sob story about my hard-luck, self-taught career, but I […]

Recursive hash operation in Ruby which fowards a block

Recursive hash operations were annoying as heck to puzzle out because, you know, functions aren’t just functions in Ruby: You have functions and procs/lambdas, all of which have subtle differences. Like a regular function cannot be passed as a block. Well, whatever, I had a problem where I had to walk, reject-from and then compact […]

Project Euler Problem #30

Problem #30 was solved on new ground: my first run through Project Euler was in rigid order of first to last ending at #25. The recent round of solutions mostly cover old ground, which works well for me by itself because it shows off how my code has improved since 2012. Also, the run of […]

Project Euler Problems #18 and #67

The new solution for Problem #18 (compared to the old one) is more elegant: I reverse and reduce the triangle in a manner that doesn’t require me to check. The solution for #67 is a bit more longform, so I turned the method I use here into an NPM package: Triangutron. const eighteen = ` […]

Project Euler Problem #36

function range(start, end) { return [...Array(end + 1).keys()].slice(start); } function palindrome(number) { return number.toString() === number.toString().split('').reverse().join(''); } function toBinary(number) { return (number >>> 0).toString(2); } function add(sum, current) { return sum + current; } const palindromes = range(1, 999999).filter(number => { return palindrome(number) && palindrome(toBinary(number)); }); console.log(palindromes.reduce(add));


I went back and owned the fuck out of Problem 24. I present to you a fully-functional functional lexicographic permutation generator generator. Hail Satan! \m/ #!/usr/bin/env node const lexicographer = require('lexicographer'); const array = [...Array(10).keys()]; const breakpoint = 1000000; let permutations = 0; for (let value of lexicographer.permute(array)) { permutations++; if (permutations === breakpoint) { […]

Project Euler Problem #16

Ruby this time, and a wee bit shorter too. (2**1000).to_s.split(//).map(&:to_i).reduce(:+)

Project Euler Problem #24

#24 defeated the fuck out of me first time through: My solution to this was basically stolen elsewhere, and it took me a whole year to come back, sit down, and work through my own solution. The poor wording (I’ve since edited it) of the Wikipedia article didn’t help me. The specific piece of information […]

Project Euler Problem #22

Again, better. :) #!/usr/bin/env node const fs = require('fs'); const add = previous, current) => previous + current; const toNumbers = string => { return string.split('').map((_, index) => string.charCodeAt(index) % 64); } fs.readFile('./p022_names.txt', 'utf8', (_, data) => { const names = JSON.parse(['[', data, ']'].join('')).sort(); const reduced =, index) => { return toNumbers(name).reduce(add) * (index […]

Project Euler Problem #12

Once again, it’s more readable than my last solution. I used a generator to get the next triangle. function divisorCount(number) { let end = Math.ceil(Math.sqrt(number)); let divisorCount = 0; for (let i = 1; i < = end; i++) { if (!(number % i)) { divisorCount += 2; } } return divisorCount; } function* triangleGenerator(number) […]

Project Euler Problem #8

Functional JavaScript is cleaner than my C# solution, for sure! const raw = '731..450'; // Snipped for clarity. const chunkSize = 13; const multiply = (previous, current) => previous * current; const largest = (previous, current) => current > previous ? current : previous; function chop(string, size, chunks) { chunks = chunks || []; if […]


Hackoberfest has made Tic-tac-toe a thing in my life. tictactoe-server opened an issue for a ES6 refactor of the solution checker. I kicked around the lengthy imperative code check and found I wanted to expand the solution, that I wanted to drop in Tic-tac-toe boards of arbitrary size, and to check them in an efficient […]