This Week in #dev (Jan 26, 2024)

Welcome to another edition of This Week in #dev, a series of posts where we bring some of our most interesting Slack conversations to the public.

Loading Data into MySQL Quickly

Matheus Richard shared a video about loading 100,000,000 rows into a MySQL database. In particular, he highlights the use of MySQL’s LOAD DATA statement, which is a very fast way to load data from a file into a table.

-- Example:
LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
  FIELDS TERMINATED BY ',' ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'
  IGNORE 1 LINES;

Rails’ prepend_before_action

Steve Polito shared a discovery in Ruby on Rails: the prepend_before_action method. It allows you to call a method before another controller action (can be useful when dealing with a before_action that is shared between controllers).

Here’s a contrived example:

class Namespace < ApplicationController
  before_action :authorize_request

  def authorize_request
    true
  end
end

class Namespace::Nested < Namespace
  before_action :set_user

  def set_user
    @user = User.find(params[:id])
  end

  # 🚨
  # We don't have access to @user yet
  # because :authorize_request is called first
  def authorize_request
    @user.admin?
  end
end

With prepend_before_action, we can call :set_user before :authorize_request:

class Namespace < ApplicationController
  before_action :authorize_request

  def authorize_request
    true
  end
end

class Namespace::Nested < Namespace
  # ✅
  # prepend_before_action will call this method
  # before it calls :authorize_request
  prepend_before_action :set_user

  def set_user
    @user = User.find(params[:id])
  end

  def authorize_request
    @user.admin?
  end
end

Turbo & OAuth Forms

Joël Quenneville discovered that Turbo can cause issues with OAuth forms due to CORS restrictions. In his experience, including Turbo in a client’s login page broke the “sign in with Google” button. Fortunately, the solution was simple: disabling Turbo drive either locally by adding a data-turbo="false" attribute in the HTML or globally by setting Turbo.session.drive = false in the JS.

Removing blank values from Enumerables

Steve Polito discussed the use of compact in Ruby to remove nil values from a hash. However, compact does not account for empty strings or hashes. To address this, he used Rails’ compact_blank, which removes nil, empty strings, and empty hashes from an Enumerable.

[1, "", nil, 2, " ", [], {}, false, true].compact_blank
# =>  [1, 2, true]

Thanks

This edition was brought to you by Joël Quenneville, Matheus Richard, and Steve Polito. Thanks to all contributors! 🎉

About thoughtbot

We've been helping engineering teams deliver exceptional products for over 20 years. Our designers, developers, and product managers work closely with teams to solve your toughest software challenges through collaborative design and development. Learn more about us.