“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay...”

Rob Lacey (contact@robl.me)
Senior Software Engineer, Brighton, UK

ActiveSupport.halt_callback_chains_on_return_false = false

Finally getting to upgrading to Rails 5.1 and there are lots of cases where we use before_* callbacks to block behaviour, most often in before_destroy to prevent a record being deleted when some conditions are met / not met. Previously Rails 5.1 allowed you to just return false in a callback to halt the callback chain. Now you must use throw(:abort).

The behaviour change was turned off by default in Rails 5.0

ActiveSupport.halt_callback_chains_on_return_false = true

So you can implement the change sooner by changing that setting in an initializer.

class Thing < ApplicationRecord
  before_create do
    throw(:abort)
  end

  before_destroy do
    throw(:abort)
  end
end

I thought initially this would result in having to cope with exceptions raised from throwing that abort rather than say checking if object.destroy returned false. However, it seems it’s just a clarification of behaviour to avoid accidental blocking.

2.3.0 :006 > Thing.create.persisted?
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
 => false 
2.3.0 :007 > reload!
Reloading...
 => true 
2.3.0 :008 > Thing.create.persisted?
   (0.1ms)  BEGIN
  SQL (0.3ms)  INSERT INTO `things` (`created_at`, `updated_at`) VALUES ('2019-01-17 08:38:24', '2019-01-17 08:38:24')
   (0.5ms)  COMMIT
 => true 
2.3.0 :009 > Thing.last.destroy
  Thing Load (0.3ms)  SELECT  `things`.* FROM `things` ORDER BY `things`.`id` DESC LIMIT 1
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
 => false 
2.3.0 :010 > reload!
Reloading...
 => true 
2.3.0 :011 > Thing.create.persisted?
   (0.1ms)  BEGIN
  SQL (0.2ms)  INSERT INTO `things` (`created_at`, `updated_at`) VALUES ('2019-01-17 08:39:29', '2019-01-17 08:39:29')
   (21.0ms)  COMMIT
 => true 
2.3.0 :010 > reload!
Reloading...
2.3.0 :014 > Thing.last.destroy
  Thing Load (0.1ms)  SELECT  `things`.* FROM `things` ORDER BY `things`.`id` DESC LIMIT 1
   (0.1ms)  BEGIN
  SQL (0.2ms)  DELETE FROM `things` WHERE `things`.`id` = 2
   (0.6ms)  COMMIT
 => #<Thing id: 2, created_at: "2019-01-17 08:39:29", updated_at: "2019-01-17 08:39:29">

Hopefully this won’t be too painful an exercise.

Elixir - Day 1

Well I installed it, and that’s good enough for me for today.

Erlang/OTP 21 [erts-10.1.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe] [dtrace]

Interactive Elixir (1.7.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>

At least my specs pass

When in doubt always write just any test. If it passes then you’re good to do into production with your fully tested to hell code.

require 'spec_helper'

RSpec.describe 'so much specs' do 
  it 'represents the level of care I put into my code' do
    expect { some bullshit }.to raise_error
  end
end

More ImageMagick examples

I needed to quickly just crop an image to a specific width and then pad the image into a square with a white background.

convert logo.jpg -gravity west -extent 480x logo-cropped.jpg
convert -background white -gravity center logo-cropped.jpg -resize 470x470 -extent 470x470 result.jpg

How do I fix has unmet peer dependency...

…and what does it even mean?

DEBUG [40866a5f] 	yarn install v1.7.0
DEBUG [40866a5f] 	warning package.json: No license field
DEBUG [40866a5f] 	warning No license field
DEBUG [40866a5f] 	[1/4] Resolving packages...
DEBUG [40866a5f] 	[2/4] Fetching packages...
DEBUG [40866a5f] 	info fsevents@1.2.4: The platform "linux" is incompatible with this module.
DEBUG [40866a5f] 	info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
DEBUG [40866a5f] 	[3/4] Linking dependencies...
DEBUG [40866a5f] 	warning "@rails/webpacker > postcss-cssnext@3.1.0" has unmet peer dependency "caniuse-lite@^1.0.30000697".
DEBUG [40866a5f] 	warning " > react-google-maps@9.4.5" has unmet peer dependency "@types/googlemaps@^3.0.0".
DEBUG [40866a5f] 	warning " > react-google-maps@9.4.5" has unmet peer dependency "@types/markerclustererplus@^2.1.29".
DEBUG [40866a5f] 	warning " > react-google-maps@9.4.5" has unmet peer dependency "@types/react@^15.0.0 || ^16.0.0".
DEBUG [40866a5f] 	warning " > webpack-dev-server@2.11.2" has unmet peer dependency "webpack@^2.2.0 || ^3.0.0".
DEBUG [40866a5f] 	warning "webpack-dev-server > webpack-dev-middleware@1.12.2" has unmet peer dependency "webpack@^1.0.0 || ^2.0.0 || ^3.0.0".
DEBUG [40866a5f] 	[4/4] Building fresh packages...
DEBUG [40866a5f] 	Done in 17.33s.

Firstly the licence warning can be removed by making the package private.

{
  "private": true,
  "dependencies": {
    "@rails/webpacker": "3.5",
    "axios": "^0.18.0",
    "babel-preset-react": "^6.24.1",
  /*... and some more ... */
}

Eager loading data and magic attributes in ActiveRecord

I am not a fan of reading a Rails log and seeing a silly number of queries to the database particularly if they are for the same thing time and time again, sometimes exactly the same query but also sometimes a similar query that’s repeated for each object in a list. Yes, you can use includes to preload associations e.g Post.includes(:something) but what about something more complex like a ratings count.

The following is your pretty average polymorphic ratings table. Each Post has multiple ratings, and you just want to show the score.

class Post
  has_many :ratings, as: :rateable

  def score
    (ratings.pluck('AVG(score)')[0] || 0).to_i
  end
end

class Ratings
  belongs_to :rateable, polymorphic: true
end

So what happens when you display this as a list, something like this….

(0.3ms)  SELECT AVG(score) FROM `ratings` WHERE `ratings`.`rateable_id` = 1 AND `ratings`.`rateable_type` = 'Post'
  Rendered posts/_post.json.jbuilder (1.6ms)
   (0.3ms)  SELECT AVG(score) FROM `ratings` WHERE `ratings`.`rateable_id` = 2 AND `ratings`.`rateable_type` = 'Post'
  Rendered posts/_post.json.jbuilder (1.6ms)</pre></code>
   (0.3ms)  SELECT AVG(score) FROM `ratings` WHERE `ratings`.`rateable_id` = 3 AND `ratings`.`rateable_type` = 'Post'
  Rendered posts/_post.json.jbuilder (1.6ms)
   (0.3ms)  SELECT AVG(score) FROM `ratings` WHERE `ratings`.`rateable_id` = 4 AND `ratings`.`rateable_type` = 'Post'
  Rendered posts/_post.json.jbuilder (1.6ms)
   (0.3ms)  SELECT AVG(score) FROM `ratings` WHERE `ratings`.`rateable_id` = 5 AND `ratings`.`rateable_type` = 'Post'
  Rendered posts/_post.json.jbuilder (1.6ms)

Not particularly efficient. With every Post you increase the number of queries to the DB. Even if that is a millisecond 1,000 Post objects later it’s a second. And seconds feel clunky in a nice swanky interface. We could include the ratings objects for each Post.includes(:ratings) but that’s not very efficient either. We just need the count not multiple new Rating objects.

We could, however, add the scores count to the SELECT query. With ActiveRecord magic anything in the SELECT turns into an attribute of the object you’re fetching in this case Post. If you’re wondering what COALESCE means here, if there are no ratings the AVG of NULL will be NULL. COALESCE returns first NOT NULL result. COALESCE will return 0.

@posts = Post
    .group(:id)
    .left_joins(:ratings).distinct
    .select('cafes.*, COALESCE(AVG(ratings.score), 0) AS score')

Then we can alter the Post#score method to check it’s attributes first.

def score
    (attributes['score'] || ratings.pluck('AVG(score)')[0] || 0).to_i
  end

So we can king of eager load results. instead of fetching them in multiple hits to the database. Cool huh? And it’s shaved off 40ms on the DB time so while in this application it’s not going to kill us, why not be efficient from the outset and not fill the log with unnecessary queries.

Completed 200 OK in 382ms (Views: 337.1ms | ActiveRecord: 42.3ms)

vs..

Completed 200 OK in 282ms (Views: 262.6ms | ActiveRecord: 4.4ms)

pad your images with a background colour in ImageMagick

In the absence of a graphics editor on this machine, I just needed a quick way of padding an image that already had a white background. This just adds additional white padding around the existing image which was about 700×1024

convert ~/Desktop/concordia.gif -gravity center -background white -extent 1600x1124 ~/Desktop/concordia-resize.jpg

Ruby #tap

Bit of Ruby fun. I really like #tap for cleaning up blocks where you assign unnecessary variables. While I admit the following examples don’t all do the same thing I noticed something this morning. The first two should have concatenated the Array and last one oappended. It’s odd that the first two examples returned an empty Array and not [1, 1, 2, 3], or [[1 ], [1, 2, 3]]

2.2.6 :018 > [].tap { |a| a += [1]; a += [1,2,3] }
 => [] 
2.2.6 :018 > [].tap { |a| a += [[1]]; a += [[1,2,3]] }
 => [] 
2.2.6 :019 > [].tap { |a| a << [1]; a << [1,2,3] }
 => [[1], [1, 2, 3]]

So, the object returned from #tap is always the one you passed in, so for a start is doesn’t return that last thing evaluated in the block. Then you realise a += 1 returns a new object and reassigns the value of a, so it can’t be the original object and therefore you’re concatenating and creating a new object that isn’t returned.

First live React project

We’ve been reworking the Boardgame Cafes Map and I think it’s come out quite well. The original map was built with multiple calls to the cafes API endpoint whenever you selected a new country it reloaded the page and data set which filtered down the results by country. The problem with this is that you couldn’t move around the map and discover cafes in the next country over or easily get back to the original full map without a costly page refresh, it felt clumsy and not very slick. With React a single call to the cafes API gives us the entire data set which we then build multiple components from, the country select list, the cafe list, the cafe markers and lightbox content.

I am sure there are many more features we can add to improve it but for now it’s relaunched and working great on desktop and mobile.

Regex matching calling method

Want to capture the calling method? Plus three different methods of extracting the match.

2.2.6 :009 > c = caller(1..1).first 
=> "/Users/roblacey/repos/something/blah.rb:192:in `pages'" 
# scan(pattern) → array
2.2.6 :014 > c.scan(/`([^']*)'$/).join
=> "pages" 
# match(pattern) → matchdata or nil
2.2.6 :015 > c.match(/`([^']*)'$/).try(:[], 1)
=> "pages" 
# str[regexp, capture] 
2.2.6 :017 > c[/`([^']*)'$/, 1]
=> "pages"