# Today I learned > Articles and learnings on Elixir, Rust, Ruby, Go, Javascript, Platform engineering, SRE. Public Ghost content for AI and LLM tooling. Use `/llms-full.txt` for consolidated page and post context. Append `.md` to any post or page URL to get the content in Markdown (for example, `/example-post.md`). ## Pages - [About this site](https://til.codes/about.md) - Today I learned is an independent publication launched in July 2024 by Manu Ajith. If you subscribe today, you'll get full access to the website as well as email newsletters about new content when it's available. Your subscription makes this site possible, and allows Today I learned to continue to… ## Posts - [Gremlins After Midnight: How 794 Git Packs Hit the macOS 256 File Limit](https://til.codes/gremlins-after-midnight-how-794-git-packs-hit-the-macos-256-file-limit.md) - A routine darwin-rebuild on Determinate Nix 3.15 died with 'Too many open files' because Nix's flake cache is a libgit2 repo, it had grown to hundreds of packs, and macOS still ships a 256 file descriptor limit to anything launchd starts. - [When the Nix Eval Cache Serves You a Ghost Derivation](https://til.codes/when-the-nix-eval-cache-serves-you-a-ghost-derivation.md) - Postgres kept booting on port 15433, but my config said 15432. I grepped the entire repo for 15433 and found nothing. The number didn’t exist in any file I had edited, yet there it was, running, confident, every single time. - [The Filter in the Wrong Place: 76x Faster by Moving One WHERE Clause](https://til.codes/the-filter-in-the-wrong-place-76x-faster-by-moving-one-where-clause.md) - A payments API ranked every transaction in the table before throwing most of the rows away, because the account-name filter ran after the window function instead of before it. - [Your Pin-to-Bottom Hook Is Missing the Users Who Need It Most](https://til.codes/your-pin-to-bottom-hook-is-missing-the-users-who-need-it-most.md) - The instinct when building a pin-to-bottom scroller is to listen for `window.resize`. Use ResizeObserver instead, see why below - [Picking Where jj absorb Lands: Adding --into to jjui](https://til.codes/picking-where-jj-absorb-lands-adding-into-to-jjui.md) - jj absorb is the command I miss most in git. Adding --into support to jjui so I can target specific ancestors from the TUI - [Bridging git worktrees and jj workspaces for agentic workflows](https://til.codes/bridging-git-worktrees-and-jj-workspaces-for-agentic-workflows.md) - My jj workspaces were invisible to Zed, Neovim, and Codex, no diff gutters, no blame annotations. The fix? A single line pointing libgit2 to the Git object store that was already there. - [LiveView Already Knows When Your Server Crashed](https://til.codes/liveview-already-knows-when-your-server-crashed.md) - This week, I reviewed a pull request that added error flash handling to a Phoenix app. The JavaScript implementation seemed straightforward: listening for phx:page-loading-start, checking the socket connection, showing a popover for server crashes, and hiding it during navigation. It included two h… - [The Magic of `jj absorb`: Rewriting History Without the Pain](https://til.codes/the-magic-of-jj-absorb-rewriting-history-without-the-pain.md) - I was fixing a typo that spanned six commits With git, that meant an interactive rebase, editing each commit, resolving conflicts. With jj, it was one command: jj absorb. - [Who Watches the Watcher? Debugging a Silent Langfuse Integration in Production](https://til.codes/who-watches-the-watcher-debugging-a-silent-langfuse-integration-in-production.md) - I deployed Langfuse for observability, but the dashboard stayed empty. Instead of redeploying with more logs, I used BEAM's :dbg to trace live function calls and hot-loaded fixes into a running Elixir system. This is the story of debugging the watcher itself. - [Flaky Playwright Tests and Phoenix: A Distributed Systems Problem](https://til.codes/flaky-playwright-tests-and-phoenix-a-distributed-systems-problem.md) - The DBConnection.OwnershipError isn't a bug. It's the BEAM telling you you're building a distributed system wrong - [Speed Racer Gone Wrong: When CUDA Graph Optimization Killed My Inference Server](https://til.codes/speed-racer-gone-wrong-when-cuda-graph-optimization-killed-my-inference-server.md) - Why did my stable vLLM server keep crashing with CUDA OOM errors? The culprit: CUDA Graphs. For diverse workloads like structured JSON, graph capture + PyTorch's cache = a slow memory leak. I fixed it with one flag: --enforce-eager. Here's why I traded performance for stability. - [Ghostbusters: Who You Gonna Call When KV Cache Eats Your GPU?](https://til.codes/ghostbusters-who-you-gonna-call-when-kv-cache-eats-your-gpu-2.md) - My model was 60GB, and my GPU had 141GB. I should have had 81GB free, but I kept hitting OOM errors. The culprit? KV cache - an unseen memory hog that consumed 68GB without showing up in any config file. This article will explore how the context window and batch size are a zero-sum game. - [Fast & Furious Tensor Parallelism: GPU Heist Gone Wrong](https://til.codes/fast-furious-tensor-parallelism-gpu-heist-gone-wrong.md) - Splitting a model across 4 H200 GPUs was expected to 4x throughput, but instead resulted in 2.8x worse latency and 35% lower throughput. Without NVLink, tensor parallelism causes more communication overhead than speedup, so sometimes 1 GPU outperforms 4 - [Honey, I Shrunk the Model: When Quantizing 70B Parameters Broke Everything](https://til.codes/honey-i-shrunk-the-model-when-quantizing-70b-parameters-broke-everything.md) - I tried to shrink a 70B model from FP16 to FP8 to fit in my 141GB of VRAM. Spoiler: it broke everything. After testing 6 models and 3 quantization formats, I discovered that a 30B model in full precision outperformed every quantized 70B. Turns out precision matters more than parameter count. - [Beyond IO.inspect: The Holy Trinity of Elixir & Phoenix Debugging with Neovim and Nix](https://til.codes/beyond-io-inspect-the-holy-trinity-of-elixir-phoenix-debugging-with-neovim-and-nix.md) - A guide on how to set up the Elixir debugger in Neovim. This post explores the complete configuration using elixir-ls and nvim-dap, with a special focus on making it work seamlessly inside a Nix development environment. - [Remapping Keys on macOS with Nix-Darwin: My Battle with the EU Keyboard Layout](https://til.codes/remapping-keys-on-macos-with-nix-darwin-my-battle-with-the-eu-keyboard-layout.md) - If you’ve ever used an EU keyboard on macOS, you know the struggle. The tilde (~) is bizarrely placed next to the Z key, and getting to a backtick (`) feels like solving a puzzle involving Shift and frustration. This post is about how I swapped the tilde and backtick keys using Nix-Darwin, hidutil,… - [Advent of Code 2024: Day 6 - Guard Gallivant](https://til.codes/advent-of-code-2024-day-6-guard-gallivant.md) - Today I dove into path finding and state machines. The problem seemed simple at first - just simulate a guard's patrol route - but it turned into a fascinating puzzle about cycle detection. I tackled it with my usual four languages - Rust, Elixir, Go, and Haskell - and each one showed me something… - [Advent of Code 2024: Day 5 - Dependencies and Ordering](https://til.codes/advent-of-code-2024-day-5-dependencies-and-ordering.md) - I found myself in the North Pole's printing department today, helping an elf with their safety manual updates. The printer had strict rules about page ordering - certain pages had to be printed before others. As I stared at the long list of rules like "47|53", I couldn't help but smile. This wasn't… - [Advent of Code 2024: Day 4 - Pattern Matching in Multiple Dimensions](https://til.codes/advent-of-code-2024-day-4-pattern-matching-in-multiple-dimensions.md) - The elves handed me what looked like a simple word search puzzle today. Find "XMAS", they said. Easy enough - until I discovered I needed to find it in every possible direction, including diagonals and backwards. Then part 2 hit me with X-shaped patterns, and suddenly I was deep in geometric territ… - [Advent of Code 2024: Day 3 - A Tale of State and Style](https://til.codes/advent-of-code-2024-day-3-a-tale-of-state-and-style.md) - Its day three of Advent of Code. Today's challenge evolved from a straightforward exercise in multiplication into an elegant dance of state management and instruction parsing. Here I am again, with Rust, Elixir, Haskell, and Go to solve it. The Challenge: A State Machine in Disguise What started as… - [Advent of Code 2024: Day 2 - When Languages Shape Our Thinking](https://til.codes/advent-of-code-day-2-when-languages-shape-our-thinking.md) - Advent of Code 2024: Day 2 - When Languages Shape Our Thinking - [Advent of Code Day 1: A Deep Dive into Language Characteristics](https://til.codes/advent-of-code-day-1-a-deep-dive-into-language-characteristics.md) - Solving Advent Of Code 2024 Day 1, using Elixir, Rust, Go and Haskell to how each language's philosophy and features guide us toward different solutions, even for the same simple problem. - [My First Adventure with Astro: A Journey from Next.js](https://til.codes/my-first-adventure-with-astro-a-journey-from-next-js.md) - Switching from Next.js to Astro for a static site? Here's my journey exploring Astro's 'zero JavaScript by default' approach, island architecture, and how it plays nicely with Cloudflare pages/workers. - [Writing Rust NIF code to convert encryption code from Elixir to Rust](https://til.codes/converting-encryption-code-from-elixir-to-rust-using-nif.md) - In this article, we will go through what a NIF is, how to write safe NIF code using Rust and Rustler - [Add latency tracking to phoenix live view apps.](https://til.codes/add-latency-tracking-to-phoenix-live-view-apps.md) - Add latency tracking to phoenix live view apps - [Running scheduled cron jobs in Rust using tokio](https://til.codes/running-scheduled-cron-jobs-in-rust.md) - Running periodic/scheduled tasks in Rust using tokio and async/await - [Making periodic http requests in Rust](https://til.codes/making-periodic-http-requests-in-rust.md) - Making http requests in Rust using reqwest, tokio, async/await and http proxies and cookies - [Configure max_connections for PostgreSQL using nix](https://til.codes/configure-max_connections-postgresql-nix.md) - How to configure max_connections value for PostgreSQL using nix - [using elixir master branch using nix and nix-shell](https://til.codes/using-elixir-master-branch-using-nix.md) - There were some noteable changes that landed on the master branch in elixir today, related to improving the compilation, and I wanted to try out the latest version of elixir that was on the master branch. Since I use nix for setting up my projects, the latest version of elixir was not yet available… - [Using variables inside binary pattern matching](https://til.codes/binary-pattern-matching-in-elixir-and-using-variables-as-pattern.md) - I was refactoring a piece of code that I inherited in a codebase, which was parsing date from an external source in various formats into Date in elixir. The initial version of parse/1 function look something like the following: defmodule DateParser do def parse( <<_day_value::binary-size(1), space_… - [Tracing in Elixir/Erlang using :erlang.trace and GenServer](https://til.codes/tracing-in-elixir.md) - Recently, I wanted to trace a running Elixir system and see the messages that a function received. I was looking to inspect the params that it received and even manipulate the params to fiddle with some edge cases in the system. I knew that I could use dbg to start a trace on the function and play… - [Deleting stale Postgres wal files](https://til.codes/deleting-stale-postgres-wal-files.md) - I was debugging a system earlier today, where one of the postgres instances ran out of disk space, and taking a closer look at the system, I realised that the backup command was failing silently, but the postgres archive files was still being retained in the wal folder. Checking a bit at the docume… - [Finding long running SQL queries in PostgreSQL](https://til.codes/finding-long-running-sql-queries-in-postgresql.md) - Recently in one of the projects that I was working on, I came across a situation where the SQL query times was getting slower and slower per day, and I had to figure out what was happening to the system. One of the things that I checked immediately was whether there were any long running queries in… - [Using custom/older versions of libraries and packages using nix.](https://til.codes/using-custom-versions-of-libraries-and-packages-using-nix.md) - Install custom or older versions of package(Ruby or Node or any other) using nix by overriding the package derivation using overrideAttrs - [nix-shell for elixir projects](https://til.codes/nix-shell-for-elixir-projects.md) - Simple nix-shell to get started with using nix as development environment with Elixir/Phoenix/Rust - [Tracing in Elixir/Erlang using dbg trips and tricks.](https://til.codes/tracing-in-elixir-erlang-using-dbg-trips-and-tricks.md) - Tips and tricks for tracing in elixir/erlang using dbg module and some helper functions. - [Custom types using dry-logic and predicates](https://til.codes/custom-types-with-dry-rb-gems.md) - Build custom types for IPv4 and IPv6 using dry-logic and predicates. - [Upgrading ghost to 3.X from 2.x](https://til.codes/upgrading-ghost-to-3-x-from-2-x.md) - Upgrading Ghost from v2.x to v3.x and fixing compatibility of ghost-cli with nodejs versions. - [Escaping special characters like & in rails Html views](https://til.codes/escaping-special-characters-like-in-rails-html-views.md) - Safely escape and render html characters while preserving special characters like ampersand(&) using strip_tags and Loofah - [Letter opener is not processing emails in rails app](https://til.codes/letter-opener-is-not-processing-emails-in-rails-app.md) - letter_opener is one of the most useful gems out there for a rails developer. The configuration is pretty much easy and straightforward. But yet I stumbled upon a situation where it stopped working. All the setup instructions were in order, but still, for some reason, the emails were not being disp… - [Fixing Rspec tests involving timestamps on CircleCI.](https://til.codes/fixing-rspec-tests-with-timestamps-in-circle-ci.md) - Use TimeCop gem or rspec be_within built in matcher to fix specs involving timestamps in CircleCI - [Tuning concurrency settings for AWS S3 CLI](https://til.codes/tuning-concurrency-settings-for-aws-s3-cli.md) - Tuning the max_concurrent_requests configuration for better performance when copying files from S3 buckets using the AWS CLI S3. - [Using X-UA-Compatible to render websites in compatibility mode.](https://til.codes/how-to-render-websites-in-compatibility-mode-using-x-ua-compatible.md) - Add X-UA-Compatible meta tags or headers to force Internet Explorer to run websites in compatibility mode. the same can be done by forcing http headers on web servers - [Fix for 100% CPU usage by node.js](https://til.codes/fix-for-100-cpu-usage-by-nodejs.md) - If you are on MacOs and you don't have installed fsevents, you might see a spike in CPU usage when running projects which watches the filesystem changes, especially projects like Webpack. To fix the issue, install fsevents or rebuild using fsevents. - [Making dependent services wait till containers are healthy using docker health check](https://til.codes/health-check-option-in-docker-to-wait-for-dependent-containers-to-be-healthy.md) - Using the health check option provided by docker we can make containers wait till the dependent containers are online and healthy - [How to make a Genstage consumer subscribe only to particular events or stream](https://til.codes/making-genstage-consumer-subscribe-only-to-particular-events-or-stream.md) - Genstage consumer can optionally subscribe to some of the events produced by the producer by using GenStage.BroadcastDispatcher as dispatcher and by specifying a :selector function which filters out the events we are interested in - [Extending the disk space on an EC2 instance](https://til.codes/extending-the-disk-space-on-an-amazon-ec2-instance.md) - How to extend disk space on an AWS EC2 instance or Elastic BeanStalk instance by extending the Elastic Block Store volume and resizing the partition - [Upgrade ghost from v0.11 to v1.0+ and tweak Casper theme layout to use list instead of cards](https://til.codes/upgrade-ghost-from-v0-11-to-v1-0-and-tweak-casper-theme-layout-to-use-list-instead-of-cards.md) - How to update ghost from version v0.11 to v1.0 and up and tweaking the default casper theme for lists instead of cards, adding syntax highlighting, and bigger fonts - [How to disable Adobe Flash Player update notification](https://til.codes/how-to-disable-adobe-flash-player-update-notification-2.md) - Well, lets not talk about the history/legacy of Flash/HTML5 etc here. Flash has its place but its really annoying when the Adobe Flash Player updater pops in when you are working on something important and distracts you. And even worse, you are presented with only option to Remind Me Later or Downl… - [Disable pry and exit debugger without killing the main program in Ruby](https://til.codes/disable-pry-and-exit-debugger-without-killing-the-main-program-in-ruby.md) - You ever ran into a situation where you had a huge loop running and you put a binding.pry within that loop for debugging and wondered how the hell you would exit the debugger? The answer is simple disable-pry is your saviour.! via GIPHY This has got its downside though, this will disable any furthe… - [Don't forget to update the sequence in PostgreSQL after a COPY command](https://til.codes/dont-forget-to-update-the-sequence-in-postgresql-after-a-copy-command.md) - You might have noticed that after bulk inserting records using the COPY statement in PostgreSQL the sequence IDs are not getting updated for any further inserts later on, and it would throw duplicate sequence ID errors. So you would be wondering what makes this COPY statement different that it does… - [Copy data from one postgres instance to another. remote copy options explored: Copy, CSV and STDIN](https://til.codes/using-postgres-copy-command-to-copy-data-from-one-server-to-another.md) - Various options to copy data from one Postgres database/table to another Postgres database or table using copy command. - [Escape character sequence "E" in PostgreSQL explained](https://til.codes/escape-character-sequence-e-in-postgresql-explained.md) - What's the "E" before a Postgres statement mean? Explaining the postgreSQL escape character sequence. - [Passing multiple options/argument with default options in rake](https://til.codes/passing-multiple-options-argument-with-default-options-in-rake.md) - Rake task allows you to accept multiple arguments which can be used within the task, and also allows us to specify default options for these arguments. Accept multiple arguments/options Lets say we have a simple rake task to sync data from/across our servers to different enviroments. We can accept… - [How to fix the Index name too long error in rails migrations](https://til.codes/how-to-fix-the-index-name-too-long-error-in-rails-migrations.md) - Today, I was reviewing some legacy code, trying to isolate the bottlenecks and pinpoint the optimisation strategies for scaling and performance optimisations of a rails app. As the usual procedure, I wanted to check the database indexes and see if something was missing here. And my guess was in the… - [Find out which part of your code is triggering ActiveRecord or SQL queries.](https://til.codes/find-out-which-part-of-your-code-is-triggering-activerecord-or-sql-queries.md) - Today, I got a new pet project to play with and my job was to identify the bottlenecks and performance improvements we can make in the application. So I wanted to jump in and wanted to see what SQL queries were being triggered when someone requests data. Going through the entire code was not a feas… - [Bypassing ssh firewall by overriding Type of Service headers for TCP packets in routers](https://til.codes/bypassing-ssh-firewall-by-overriding-type-of-service-headers-for-tcp-packets-in-routers.md) - I was recently having issues when trying to ssh into one of my servers. The normal debugging techniques and solutions didn't work for me and I had to debug this in depth to figure out the issue was actually with my router blocking the packets The actual problem.! When you ask for a regular ssh term… - [Debugging Git network connection issues using GIT_TRACE](https://til.codes/debugging-git-network-connection-issues-using-git_trace.md) - I have been travelling a lot this month and working remotely from cafes and public places during my stay in Europe. And most often I was connected to the internet using the public hot spots or free Wifi provided by the cafes or restaurants. The quality of the connections were really good I must adm… - [Script/runner vz Rake tasks](https://til.codes/script-runner-vz-rake-in-cron-job-rails.md) - When it comes to running Rails tasks the common question that comes to mind is whether to use script/runner or to call a rake task script/runner long_running_task VZ rake long_running_task To understand it better we need to understand how both works under the hood. Whenever script/runner is called… - [Elegant way to silently ignore a Ruby exception](https://til.codes/which-is-the-shortest-way-to-silently-ignore-a-ruby-exception.md) - I was working on a small hobby project and wanted to ignore some of the Exceptions that were raised. The first version of the code that I wrote was something similar to: def ignore_exception begin yield rescue Exception end end and using ignore_exception { puts "Ignoring Exception"; raise Exception… - [brew cask: Error: Unknown command: cask](https://til.codes/brew-cask-error-unknown-command-cask.md) - After upgrading my OS to Sierra I was having an issue with homebrew. It failed to recognize the cask command and was throwing an error: brew cask install haskell-platform Error: Unknown command: cask Brew wasn't able to find the correct path and was causing this issue. Fix: brew update brew cleanup… - [Manage sidekiq workers using deployment setup and Capistrano](https://til.codes/manage-sidekiq-workers-using-deployment-setup-and-capistrano.md) - In real world, most of the Rails applications would be having a Sidekiq instance as its companion in production systems. And it's a necessary thing to have some sort of mechanism to manage your Sidekiq instance with your deployment setup. In this post, I am going to throw light on some of the optio… - [How to turn on SQL debug logging for ActiveRecord](https://til.codes/how-to-turn-on-sql-debug-logging-for-activerecord.md) - If you want to see the SQL queries that your apps are running and want o optimize them or tune them, then it is a nice idea to log them. You can either log it to your log file or even to STDOUT. You can set the log level in your environment file to debug so that you can get maximum data out of your… - [How to fix Npm install failed with "cannot run in wd"](https://til.codes/npm-install-failed-with-cannot-run-in-wd-2.md) - I was trying to upgrade my blogs ghost version to 0.9(which btw has some cool features) and I stumbled upon an issue when trying to upgrade the packages. Every time I run sudo npm install --production on my server, I get the following error: npm WARN cannot run in wd ghost@0.9.0 node core/server/ut… - [Copy file from host machine to docker container](https://til.codes/copy-file-from-host-machine-to-docker-container.md) - The docker cp utility copies the contents of SRC_PATH to the DEST_PATH. You can copy from the container’s file system to the local machine or the reverse, from the local filesystem to the container. If - is specified for either the SRC_PATH or DEST_PATH, you can also stream a tar archive from STDIN… - [How to load rake task from a custom file or directory](https://til.codes/load-rake-files-and-run-tasks-from-other-files.md) - If you are wondering how you can load a rake task from a custom file, then this is guide will help you to accomplish your task. Lets assume you have a rake task named hello.rake under your project directory's lib folder like: /lib/tasks/hello.rake Then you can create a simple Makefile in y… - [docker-compose up is slow on docker for mac os beta](https://til.codes/docker-compose-slow-on-docker-for-mac-os-beta.md) - I have been trying with Docker beta on Mac OS and was facing an issue with docker-compose. It was taking ages for the docker-compose commands to get executed. After digging into a while I figured out that the dns lookup was causing the issues. docker-compose is trying to resolve localunixsocket.loc… - [Injecting auth-headers into angular.js application using http.config vz using interceptors.](https://til.codes/injecting-auth-headers-into-angular-js-application-using-http-config-vz-using-interceptors.md) - We have been building a client app in Angular.js and decided on using token auth with JWTs, pretty much the normal choice. We got everything set up on the server side and am receiving the token on the client side, but now we just need to send the token with every request. At this point, our front-e… - [How to enable support for CORS with custom headers like authentication in Rails](https://til.codes/how-to-enable-support-for-cors-with-custom-headers-like-authentication-in-rails.md) - I was building a client side application for my API that I built using Rails/Grape. So in order to access the resources using the API from the client application the first thing that I need to do was to enable CORS support in the API. Enabling CORS using rack-cors gem I did everything as was said i… - [How to install a specific package version in Alpine and Docker?](https://til.codes/how-to-install-a-specific-package-version-in-alpine-and-docker.md) - I was building a docker image for a backend API application that I was working on, so that my colleague, who is a front-end guy can easily setup the docker container and get it up and running. I chose Alpine Linux to build the Docker image bcos its light weight. I started adding dependencies to the… - [TDD in Elixir with ExUnit and Doctest](https://til.codes/tdd-in-elixir-with-exdoc-and-doctests.md) - ExUnit & DocTest Elixir has it's own test framework built in natively, called ExUnit. ExUnit is a core component of Elixir itself, as much as the task runner and dependency manager mix. When you start a new project with mix, everything is directly set up for you, including basic unit tests for your… - [How to fix Incomplete response received from application from nginx / passenger in a rails application](https://til.codes/how-to-fix-incomplete-response-received-from-application-from-nginx-passenger-in-a-rails-application.md) - I was trying to deploy a simple rails application( stack is Ruby 2.2.4, Rails 4.2.5, with passenger/Nginx as application/web server) to AWS EC2 and I was getting a weird error. Incomplete response received from application And looking at the Nginx/passenger logs I wasn't able to figure out the issu… - [Tail Call Optimisation](https://til.codes/tail-call-optimisation-eplained.md) - Tail Call Optimization is the process by which a smart compiler can make a call to a function and take no additional stack space. The only situation in which this happens is if the last instruction executed in a function is a call to another function or the function itself. The most common use is t… - [Active Model Serializer vz Jbuilder vz Rabl vz Grape-entity for rendering JSON](https://til.codes/active-model-serializer-vz-jbuilder-vz-rabl-vz-grape-entity-vz-roar.md) - When architecting an API only application one the of the most important points of discussion among the team members is which framework to use ? * Should we be using Rails and render JSON ? * Should we be using Grape ? * Should we be using Rails-API ? Also, how are we gonna format the JSON responses… - [Error handling with Grape, Rails and ActiveRecord CanCan](https://til.codes/error-handling-with-grape-rails-and-activerecord-cancan.md) - I have been working on a project developing the backend API using Rails and Grape. One fine morning I pulled the latest code from the git repo that my colleague wrote, and was going to review the code. As usual, the first thing I did was to run the Integrations specs and to my surprise, some of the… - [Using helper methods and helper modules in Rails Grape to keep the code DRY](https://til.codes/using-helper-methods-and-helper-modules-in-rails-grape-to-keep-the-code-dry.md) - I was working with a Grape API and got into a situation where I was kind of reimplementing some methods on more than one mounted API. So naturally, I wanted to refactor the code, keep it DRY and extract it as helper methods and eventually into helper module. So here is what my base API class looks… - [JSON Web Tokens explained and how to use JWT in authentication with APIs](https://til.codes/json-web-tokens-explained-and-how-to-use-jwt-in-authentication-with-apis.md) - Introduction Over the last few years web application development has seen drastic changes, with the front-end frameworks coming to the scene, the popularity of hybrid applications, mobile first strategy, rising demand for SPAs, Microservices etc. In older times, both the frontend and the backend wo… - [Docker difference between run, cmd, entrypoint commands](https://til.codes/docker-run-vs-cmd-vs-entrypoint.md) - If you have built a docker image, you would be familiar with the commands RUN, CMD, ENTRYPOINT. While some of you know what these means, where to use those and when to use those, there are some who might not know the exact difference between those commands. These commands are quite similar and can… - [Behaviours in Elixir explained](https://til.codes/behaviours-in-elixir-explained.md) - Behaviours provide a way to define an interface which a module can implement. A module declares that it implements the Behaviour with the @behaviour annotation. The functions in the modules implementing the behaviour will be checked at compile time to see if they match the function specifications i… - [require vz import vz use vz alias directives in Elixir](https://til.codes/require-vz-import-vz-use-vz-alias-directives-in-elixir.md) - One of an essential feature of a language when developing software is to reuse the code or the modules. What are directives ? So directives are a way via which we can reuse our code, import it and use it with other modules. What are the available directives in Elixir When it comes to elixir, we are… - [Install, configure and use git hooks to automate your workflow with distributed team](https://til.codes/install-configure-and-use-git-hooks-to-automate-your-workflow-with-distributed-team.md) - My team uses Git as the center of our development process, leveraging all those cool features git provides us - git workflow, feature branching, switching branches for code reviews, Pull Requests and all such cool stuff. Using git is an integral part of our workflow, which means all the development… - [Rails : Devise : Send different Emails for Confirmation based on the presence of attribute or parameter](https://til.codes/rails-devise-send-different-emails-for-confirmation-based-on-the-presence-of-attribute-or-parameter.md) - So what am I up to today? - I thought of scribbling down some pieces of code that I wrote to help one of my interns in my company to help complete a task. I was juggling with my daily work and I suddenly got a ping in our slack team Hey can you please advise me on how to use separate mailer templat… - [Share button not working in Safari on OSX El-Capitan](https://til.codes/safari-share-button-not-working-on-osx-el-capitan.md) - Share button not working in Safari on OSX El-Capitan Since upgrading to the new El Capitain I have not been able to use the share button, one of the features that I liked the most with Safari. The strange thing was that it was working on my mac mini, while only my Macbook pro had the issue. So, I d… - [Testing carrierwave file uploads with RSpec and FactoryGirl.](https://til.codes/testing-carrierwave-file-uploads-with-rspec-and-factorygirl.md) - TLDR; In this blog post, I am gonna focus only on testing carrierwave. So if you are looking for instruction on installing/setting up carrierwave in your project I would suggest you looking at the carrierwave's wiki over here. So let's assume we have everything setup, in our rails application, We h… - [fizzbuzz in elixir using OTP and GenServer](https://til.codes/fizzbuzz-in-elixir-using-otp-and-genserver.md) - Speaking of Erlang/Elixir the first thing that comes to mind is OTP. The erlang veterans would definitely playing around with it on a daily basis, but to the novice, it would sound a relatively strange term, and would be wondering what this is. So I thought of scribbling down something around this… - [Some best practices while developing meteor.js apps](https://til.codes/meteor-js-best-practices-and-techniques.md) - Recently I was working as a consultant for a meteor.js app, reviewing the entire codebase, and came across some of the common mistakes the developer makes when writing his/her first meteor.js app. Though some of them are trivial, some others can have bigger consequences on the security of the appli… - [RVM error when starting zsh __rvm_cleanse_variables: function definition file not found](https://til.codes/rvm-error-when-starting-zsh-rvm_cleanse_variables-function-definition-file-not-found.md) - I was getting this error when opening new zshell: __rvm_cleanse_variables: function definition file not found command not found: rvm_error Running the following solved the problem: rm -f ~/.zcompdump* Note: The * is incase there are multiple .zcompdump files. So what goes behind the scenes: ZSH use… - [Run the last shell command with sudo](https://til.codes/run-the-last-shell-command-with-sudo.md) - I often an into the situation where I type in a long command, hit enter and then figure out that I needed to run that command as root user. Instead of typing the same command with sudo prefixed we can do the same thing using a shortcut. To run the last command 'as is', you can just do $ !! If you w… - [How do I get a process to run in the background?](https://til.codes/how-do-i-get-a-process-to-run-in-the-background.md) - Simple / Usable things first If you want a start script without much effort, you could use the upstart service. See the corresponding manual page and /etc/init/*.conf for examples. After creating such a process you can start your server by calling service my server start If you want more features,… - [Remove Untagged Images From Docker](https://til.codes/remove-untagged-images-from-docker.md) - To delete all untagged images: docker rmi $(docker images -q --filter "dangling=true") - [Docker: Remove all images and containers](https://til.codes/docker-remove-all-images-and-containers.md) - To delete all the containers we have created so far: docker rm $(docker ps -a -q) To delete all the images in docker: docker rmi $(docker images -q) NB: Deleting docker containers and images is not reversible. Make sure you know what you are upto. Ref: Docker Issue - [Restricting users signup to a particular domain in meteor.js](https://til.codes/restricting-users-signup-to-a-particular-domain-in-meteor-js.md) - If you want to restrict the user registration to a particular domain only, say for e.g.: codingarena.in, then you can do the same by adding the following code: Accounts.config({restrictCreationByEmailDomain:'codingarena.in'}); - [Git fatal: remote origin already exists](https://til.codes/git-fatal-remote-origin-already-exists.md) - One of my colleagues was facing an issue with git, trying to add a remote to the git repo. ➜ repo_name git:(master) git remote add origin git@github.com:username/repo_name.git fatal: remote origin already exists. As the error message indicates, there is already a remote configured with the name ori… - [How to Fix [ERROR] Unknown/unsupported storage engine: InnoDB](https://til.codes/how-to-fix-error-unknownunsupported-storage-engine-innodb.md) - After playing around with my MySQL configuration file in my docker container, MySQL was throwing a weird error, and was failing to start. I checked the error logs and found an entry in the error log. [ERROR] Plugin ‘InnoDB’ init function returned error. [ERROR] Plugin ‘InnoDB’ registration as a STO… - [Format time using moment.js in meteor](https://til.codes/format-time-using-moment-js-in-meteor.md) - If you want to format a time field from you database, say for e.g.: createdAt, the following helper can be used. UI.registerHelper('formatTime', function(context, options) { if(context) return moment(context).format('MM/DD/YYYY'); }); An alternate way would be to write a helper for one particular v… - [Masonry in meteor.js](https://til.codes/masonry-in-meteor-js.md) - Code snippet to make masonry work with meteor.js Template.activity_feed.rendered = function () { $('.masonry-container').isotope({ itemSelector: '.item', layoutMode: 'masonry', masonry: { columnWidth: 200, gutterWidth: 5 } }) }; - [Visualise your Gemfile dependencies](https://til.codes/visualize-your-gemfile-dependencies.md) - If you ever wanted to visualise the gem dependencies of in your ruby/rails app, then bundler is there for rescue. Type in the following from your terminal: bundle viz Viz generates a PNG file of the current Gemfile as a dependency graph. Viz requires the ruby-graphviz gem (and its dependencies) to… - [Connecting Ruby & Active Record Without Rails](https://til.codes/connecting-a-ruby-app-to-active-record-without-rails.md) - require 'active_record' require 'mysql2' # or 'pg' or 'sqlite3' # Change the following to reflect your database settings ActiveRecord::Base.establish_connection( adapter: 'mysql2', # or 'postgresql' or 'sqlite3' host: 'localhost', database: 'your_database', username: 'your_username', password: 'you… - [Best way to make a shell script daemon?](https://til.codes/best-way-to-make-a-shell-script-daemon.md) - I wanted to run a shell script as a daemon, and I was exploring SO as usual, and one of the answers that I found interesting and that fits my use case was: (./install.sh &) & Ref: to the original question here. - [Postgresql: How to find pg_hba.conf file using Mac OS X](https://til.codes/postgresql-how-to-find-pg_hba-conf-file-using-mac-os-x.md) - To find the postgresql config file we can use the locate command. Type the following in your terminal: locate pg_hba.conf Or else: If you have a postgres server running on your machine, you can find the config directory using the following command ps aux | grep postgres which would show something s… - [Dump PostgreSQL without owner and privileges](https://til.codes/dump-postgresql-without-owner-and-privileges.md) - If you ever wanted to dump your postgres development database without the owner and the privileges, then you just need to run the following command: pg_dump database_name -O -x > output_file - [Start Phoenix app with cowboy server on different port](https://til.codes/start-phoenix-app-with-cowboy-server-on-different-port.md) - To run phoenix app on a custom port other than port 4000, tweak your config file for respective environment(dev/prod/test) to the following: config :my_app, MyApp.Endpoint, http: [port: {:system, "PORT"}], Then from the terminal: $ PORT=4001 mix phoenix.server $ PORT=4002 mix phoenix.server Enjoy.! - [Problem installing puma on OS X with openssl](https://til.codes/problem-installing-puma-on-os-x-with-openssl.md) - When installing puma on OSX 10.11 El Capitan, if you are facing issues compiling mini_ssl.c fatal error: 'openssl/bio.h' file not found. all you need to do is to specify --with-opt-dir You can make this applicable for all your Gemfiles: bundle config build.puma --with-opt-dir=/usr/local/opt/openssl… - [Run Multiple Skype clients on Mac OS X?](https://til.codes/run-multiple-skype-clients-on-mac-os-x.md) - Just run the following command in terminal: open -na /Applications/Skype.app --args -DataPath /Users/$(whoami)/Library/Application\ Support/Skype2 - [Creating tables and problems with primary key in Rails](https://til.codes/creating-tables-and-problems-with-primary-key-in-rails.md) - If you run into the following error when running a migration in your legacy Rails app with MySQL 5.7 or above rake aborted! "Mysql2::Error: All parts of a PRIMARY KEY must be NOT NULL:" the fix is by monkey patching the MySQL Adapter using the following code. # lib/patches/abastract_mysql_adapter.r… - [Easy way pull latest of all git-submodules](https://til.codes/easy-way-pull-latest-of-all-git-submodules.md) - Often large projects have dependencies on many other 3rd party libraries. Each library can be a separate repo that can be brought into the dependant project as a submodule. During development, if ever you want to just go grab the latest version of every dependant submodule, type in the following co… - [Hibernate not working 15.04](https://til.codes/hibernate-not-working-15-04.md) - To know your swap partition, run swapon -s. Let's say it reports /dev/sda5. Open /etc/default/grub and find the line with GRUB_CMDLINE_LINUX_DEFAULT=. This is the list of kernel command line options GRUB will pass to Linux. Add resume=/dev/sda5, so the line GRUB_CMDLINE_LINUX_DEFAULT="nosplash enab… - [Pundit for authorization with Rspec Rails](https://til.codes/pundit-for-authorization-with-rspec-rails.md) - Authorization is one of the important feature of any web app. With rails you can leverage the power of all those wonderful open source gems that are available to you or you can code your own authorization module. The most commonly used gems for authorization are Pundit and Cancan (now cancancan, si… - [Manually insert users from seed file with accounts-password](https://til.codes/seeding-users-in-meteor-js-and-account-password.md) - One of the easiest way to seed users/admin-user into the system is by running the following on the server when it starts: Meteor.startup(function() { if (Meteor.users.find().count() === 0) { Accounts.createUser({ username: 'test', email: 'me@til.codes', password: 'password' }); } }); - [Postgres could not connect to server](https://til.codes/postgres-could-not-connect-to-server.md) - $ psql psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? The reason for the issue is because a pid file was blocking postgres from starting up. To fix it: rm /usr/local/var/postgres/postma… - [Ruby: delete multiple hash keys](https://til.codes/ruby-delete-multiple-hash-keys.md) - Returns a hash that includes everything but the given keys. hash = { a: true, b: false, c: nil} hash.except(:c) # => { a: true, b: false} hash # => { a: true, b: false, c: nil} This is useful for limiting a set of parameters to everything but a few known toggles: @person.update(params[:person].exce… - [“bin/rails: No such file or directory” w/ Ruby 2 & Rails 4 on Heroku](https://til.codes/binrails-no-such-file-or-directory-w-ruby-2-rails-4-on-heroku.md) - Rails apps with version 4 or above has some files under the bin folder namely bundle, rails, rake, setup, spring. But since I had bin folder gitignored, these files dint make it to heroku. To fix this: Remove bin from ~/.gitignore Run bundle install or rake rails:update:bin Commit your changes with… - [SET GOPATH environment variable on Ubuntu?](https://til.codes/how-do-i-set-the-gopath-environment-variable-on-ubuntu.md) - Just add the following lines to ~/.bashrc export GOROOT=/usr/lib/go export GOPATH=$HOME/go export PATH=$PATH:$GOROOT/bin:$GOPATH/bin - [Calling View helper methods from Controller / Model in Rails](https://til.codes/calling-view-helper-methods-from-controller-model-in-rails.md) - Recently I was researching a way to use link_to inside my Rails 3 controller, and learned about the method view_context. So if you ever want to access view helper methods from controller / models in rails 3 you have to use view_context method. Example view_context.link_to 'Link', link_path(@link)}.… - [Email notification when someone logs in via SSH](https://til.codes/email-notification-when-someone-logs-in-via-ssh.md) - To setup email notification, login to your server as root. Edit .bashrc vim .bashrc add the following line at the end, changing "ServerName" to the host-name of your server and "me@til.codes" to your own email address. echo 'ALERT - Root Shell Access (Server-name) on:' `date` `who` | mail -s "Alert… - [How do I make --no-ri --no-rdoc the default for gem install?](https://til.codes/how-do-i-make-no-ri-no-rdoc-the-default-for-gem-install.md) - If you are deploying to a server, or you do not want to wait around for rdoc and ri to install for each gem, you can disable them for gem installs and updates. Just add the following line to your ~/.gemrc or /etc/gemrc: gem: --no-rdoc --no-ri or gem: --no-document or if want to be more specific, in… - [How to update git remotes](https://til.codes/how-to-update-git-remote.md) - To list the existing remotes, we can use the following command: git remote -v #View existing remotes origin https://github.com/user/repo.git (fetch) origin https://github.com/user/repo.git (push) Use the following command to set the remote to a new end point. git remote set-url origin https://githu… ## Optional - [RSS Feed](https://til.codes/rss/) - [Sitemap](https://til.codes/sitemap.xml) - [Full content of pages and posts](https://til.codes/llms-full.txt)