Mark Grealish

Cats and wizardry.


stuff

Remap a JavaScript Object

Eh, gods, this one bothered me a fair bit. At work our API returns some data that I’ve found I have to remap. As it happens with any organically-grown system, there are a number of small inconsistencies between different objects with similar attributes. For example: interface Foo { ices: { type: 'vanilla'; } } interface […]

Seljalandsfoss Cloning Before/After

In my post about Sk√≥gafoss, I mentioned that I spent a few tedious hours in Photoshop cloning out tourists. This led to some questions from my friend Duncan about the time I put in to remove the tourists, which in turn put it into my head to upload this. There really were a million of […]

Git Alias to Flag Files Unchanged

Inspired by a question on Stack Overflow, “Can I get a list of files marked –assume-unchanged?”, this alias allows me to glob mark files as unchanged (or changed) from the command-line. [alias] unchanged = !git ls-files -v | grep \"^[[:lower:]]\" thaw = "!git update-index --no-assume-unchanged $@" freeze = "!git update-index --assume-unchanged $@" As an example […]

Cast Any Value as an Array in JavaScript

Another stupid little thing. In JavaScript you can use Array.from() or the spread syntax to create a shallow copy of an array or other iterable object, e.g. Array.from(foo) // [foo] [...foo] // [foo] However you can’t perform this with simple values: Array.from(9); // [] [...9] // Uncaught TypeError: 9 is not iterable The good old […]

Coffee is Good

Currently writing a client < => server HTTP service and added some test code along the lines of “When the application starts, please GET a list of all records from the server. After you receive them DELETE the first item in the list.” Promptly forgot about it. Why ever, I wondered ten minutes later, does […]

Set Zsh Tab Title Automatically Based on Folder

My current task at work sees me rewriting an old application from scratch. A good part of this involves me going back and forth between the old and new project folders-call them “wigwam” and “spaklepony”-to compare code. This can be difficult to keep straight in tabs as a terminal user. A quick walk of Stack […]

Replace Odd Numbers of Spaces Only

Stolen from Stack Overflow, this bit of regex matches odd numbers of spaces only. Last week I retabbed a work project, but didn’t catch that I replaced \t with \s instead of \s\s. Whoops. gsed -E -i -e 's/^\s(\s\s)*/& /g' src/**/*.* Per the SO link, x(xx)* will match odd numbers of x. It works.

factory_bot Email Factory

While hardly a world-shattering bit of code, I’ve found this super useful for reuse. :D FactoryBot.define do factory :email_address, class: String do skip_create transient do sequence(:address) { |n| "factory_email_#{n}@example.com" } end initialize_with do new address if address end end end Call inside a factory thus: FactoryBot.define do factory :foobar do email { create :email_address } […]

Nicely (and Recursively) Stringify a Hash’s Keys and Values

Works in Ruby on Rails versions >= 4 and in Ruby 2.5. This has really annoyed the shit out of me. I want to stringify keys and values individually, not turn an entire hash or array into a string. def deep_stringify(object) case object when Hash object.transform_keys(&:to_s).transform_values { |val| deep_stringify val } when Array object.map { […]

Better Version of Bash/ZSH Dependency Tester

Why test for one dependent executable when you can test for them all? It came in useful at work today. function _has { for PROGRAM in "$@"; do if [[ $(which $PROGRAM > /dev/null 2>&1; echo $?) != 0 ]]; then return 1 fi done return 0 }

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 […]

My Body is Ready

\\//

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 127.0.0.1 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

One easy solution for all of life’s little problems

alias fuck='sudo !!'

UX Matters

We read left-to-right. We’re trained to click left-first. Worse, the fucking unhappy path is green. I clicked this “unhappy” three times on three orders before I realized their shit. Edit: On second thoughts, this is asshole design. Make it easy for customers to leave negative responses, then use the bogus data to upsell on services.

Clarkian Magic

I live in somebody’s fictional future. Science fiction writers follow a process. First, they decide where their story will be on the spectrum of happiness-utopia or dystopia? Second, they construct a narrative history which links here and there. And finally, the writer exaggerate their made-up tomorrow for dramatic effect. The writer makes sure you know […]

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 […]

Some shit you cannot make up

I mean, while David Zindell did make up this shit, I didn’t make up my telling of it. Before you lies a description of the mighty dick of a race of hermaphroditic transhuman seal-people.

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)