Skip to content

Instantly share code, notes, and snippets.

View esquinas's full-sized avatar

Enrique Esquinas esquinas

  • Asturias, Spain
View GitHub Profile
@esquinas
esquinas / test_n_plus_ones_spec.rb
Last active January 25, 2024 15:40
Tests N+1 queries in Rails using RSpec
# frozen_string_literal: true
RSpec.describe TestNPlusOnes do
describe "<something>" do
subject(:generate) { puts("<Do something with the DB>") }
# Technique seen in ActiveRecord's #assert_queries_count to use with Minitest:
# https://github.com/rails/rails/blob/0496a5f994f134695bf7bdc02dacdf24925bc67c/activerecord/lib/active_record/testing/query_assertions.rb#L99
it "avoids N+1 queries" do
number_of_queries = 0
counter = ->(*, payload) {
@esquinas
esquinas / sql_fiddling.sql
Last active September 2, 2022 15:35
How to play with SQL with no actual table (POSTGRES flavor)
-- WINDOW EXAMPLE:
SELECT id
, col1
, col2
, bool_col
, datecuen
, (CASE WHEN bool_col IS NOT NULL
THEN SUM(col1) OVER win1
+ SUM(col2) OVER win1
ELSE 0
@esquinas
esquinas / cantor_functions.rb
Created September 29, 2021 12:14
Ruby implementation of the Cantor pairing function to uniquely encode two natural numbers into a single natural number while being order sensitive.
# LINK: https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function
# LINK: https://www.cantorsparadise.com/cantor-pairing-function-e213a8a89c2b
def inv_cantor(z)
w = ((Math.sqrt(8.0*z.to_f + 1.0) - 1.0) / 2.0).floor
t = (w**2 + w) / 2
y = (z - t)
x = (w - y)
[x, y]
end
@esquinas
esquinas / json_create_additions_example.rb
Last active May 7, 2021 09:38
Example for Ruby JSON.parse option create_additions?
require 'json'
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
@esquinas
esquinas / mongo_id_from_date.rb
Last active December 24, 2020 10:59
Convert a timestamp to MongoDB ObjectId to get fast (indexed) create_at queries for free.
# USAGE:
# ------
# mongo_id_from_date Date.parse('2020-12-24') # => "5fe3da000000000000000000"
# mongo_id_from_date(Time.now) # => "5fe471d90000000000000000"
def mongo_id_from_date(date)
min_date = Time.at 0
max_date = Time.at 0xffffffff
raise "Error: date must be between #{min_date.to_date} and #{max_date.to_date}" if date < min_date || date > max_date
@esquinas
esquinas / gist:3291de1c711fa6816daedddf3402e9bd
Created December 9, 2020 14:34
Script to check ruby syntax of all Ruby files in project directory.
#!/usr/bin/env bash
echo 'STATIC-CHECKING RUBY SYNTAX OF ALL RB & RAKE FILES IN PROJECT'
echo
find . | grep ".*\.rb$" | xargs -L 1 ruby -c
find . | grep ".*\.rake$" | xargs -L 1 ruby -c
@esquinas
esquinas / number_to_base64.rb
Last active August 25, 2020 15:37
Convert integers (or hex ids) into url-safe base64 strings saving space compared to hexadecimal (like Mongo) IE: "b380d04df5a7ea1d22cc4a54" could be passed as "s4DQTfWn6h0izEpU" in an url param saving 8 characters.
# frozen_string_literal: true
require 'base64'
def number_to_base64(number, base: nil)
valid_base = ->(b) {
b.is_a?(Integer) && b > 1
}
hex2int = ->(hex_chars) {
hex_chars.to_i(16)
@esquinas
esquinas / hybrid-example.rb
Created July 20, 2020 12:23
Best-of-both-worlds example (DI + hard-coded constants) from this article: https://www.rubypigeon.com/posts/dependency_injection_containers_vs_hardcoded_constants/
# Usage:
# - To load default dependencies: `register_user = RegisterUser.build`
# - To inject own dependencies (for testing or reuse):
# ```rb
# register_admin = RegisterUser.new(validator: AdminValidator.new, repo: AdminRepository.new)
# ```
class RegisterUser
attr_reader :validator, :repo
def self.build
@esquinas
esquinas / hash_to_struct.rb
Last active July 23, 2020 13:18
Monkeypatch to mock this feature https://bugs.ruby-lang.org/issues/16986 but using a Hash#to_struct method.
# Usage:
# my_struct = { alpha: 1, beta: 2, 'charlie' => 3 }.to_struct
# my_struct.alpha # => 1
# my_struct.beta # => 2
# my_struct.charlie # => 3
# Remember, to compare structs: `my_struct.to_h == other_struct.to_h`
#
# Usage to get deep structs:
# my_deep_struct = {
# email: 'alice@example.com',
@esquinas
esquinas / el_quijote_utf8.txt
Last active April 17, 2020 18:08 — forked from jsdario/el_quijote.txt
El Quijote en texto plano, UTF-8 y CRLF (final de línea de Windows)
This file has been truncated, but you can view the full file.
DON QUIJOTE DE LA MANCHA
Miguel de Cervantes Saavedra
PRIMERA PARTE
CAPÍTULO 1: Que trata de la condición y ejercicio del famoso hidalgo D. Quijote de la Mancha
En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lentejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas con sus pantuflos de lo mismo, los días de entre semana se honraba con su vellori de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años, era de complexión recia, seco de carnes, enjuto de rostro; gran madruga