Skip to content

Instantly share code, notes, and snippets.

View shkrt's full-sized avatar

Ruslan Gafurov shkrt

View GitHub Profile
@ProGM
ProGM / arel_cheatsheet_on_steroids.md
Last active May 16, 2025 15:55
Arel cheatsheet on Steroids

Arel Cheatsheet on Steroids

A (more) complete cheatsheet for Arel, including NamedFunction functions, raw SQL and window functions.

Tables

posts = Arel::Table.new(:posts)
posts = Post.arel_table # ActiveRecord

Table alias

@komasaru
komasaru / calc_rcc_spearman.rb
Created January 28, 2020 02:49
Ruby script to calculate a Spearman's Rank Correlation Coefficient.
#! /usr/local/bin/ruby
class Array
def rcc_spearman(y)
# 以下の場合は例外スロー
# - 引数の配列が Array クラスでない
# - 自身配列が空
# - 配列サイズが異なる
# - 数値以外のデータが存在する
raise "Argument is not a Array class!" unless y.class == Array
@andersevenrud
andersevenrud / alacritty-tmux-vim_truecolor.md
Last active May 10, 2025 22:15
True Color (24-bit) and italics with alacritty + tmux + vim (neovim)

True Color (24-bit) and italics with alacritty + tmux + vim (neovim)

This should make True Color (24-bit) and italics work in your tmux session and vim/neovim when using Alacritty (and should be compatible with any other terminal emulator, including Kitty).

Testing colors

Running this script should look the same in tmux as without.

curl -s https://gist.githubusercontent.com/lifepillar/09a44b8cf0f9397465614e622979107f/raw/24-bit-color.sh >24-bit-color.sh
@kazimzaidi
kazimzaidi / pre-commit
Created August 28, 2018 02:23
git pre-commit hook to run rubocop on changed files
#!/usr/bin/env ruby
require 'english'
require 'rubocop'
ADDED_OR_MODIFIED = /A|AM|^M/.freeze
changed_files = `git status --porcelain`.split(/\n/).
select { |file_name_with_status|
file_name_with_status =~ ADDED_OR_MODIFIED

Пример рефакторинга с использованием транзакций

Опять рассмотрим tasks#create экшен.

В экшене 3 разных логики, которые выполняются последовательно:

  1. валидация данных - необходимый шаг;
  2. сохраниение таска - необходимый шаг, если какая-то ошибка, необходимо возвращать failed значение;
  3. отправка нотификаций - мы не хотим, что бы наша транзакия не выполнялась, если отправка нотификации не выполнится;

Поэтому напишем нашу транзакцию. Так же мы будем использовать Either монаду для возвращения статуса шага транзакции. Right для успешного, Left - не успешного:

@emiliorizzo
emiliorizzo / purge-auth.vcl
Last active August 15, 2022 12:02
Varnish configuration, purge only for basic auth users
# Varnish configuration
# Purge only for basic auth users
## HOW TO PURGE
### with browser
# 1 - Set basic auth on /auth (or change the rule)
# 2 - Authenticate on /auth, and load url to refresh (purge) cache.
### with wget
@mankind
mankind / rails-jsonb-queries
Last active May 3, 2025 05:37
Ruby on Rails-5 postgresql-9.6 jsonb queries
http://stackoverflow.com/questions/22667401/postgres-json-data-type-rails-query
http://stackoverflow.com/questions/40702813/query-on-postgres-json-array-field-in-rails
#payload: [{"kind"=>"person"}]
Segment.where("payload @> ?", [{kind: "person"}].to_json)
#data: {"interest"=>["music", "movies", "programming"]}
Segment.where("data @> ?", {"interest": ["music", "movies", "programming"]}.to_json)
Segment.where("data #>> '{interest, 1}' = 'movies' ")
Segment.where("jsonb_array_length(data->'interest') > 1")
@aayubkh
aayubkh / huawei_e8372_config.md
Last active February 13, 2024 11:55
Huawei E8372 Linux Configuration and Setup

Dependencies

  1. usb_modeswitch, usb_modeswitch-data
  2. libusb1
  3. libusb-devel(Fedora), libusb-dev(Debian based)

Configuration

By default, your linux box would register your Huawei E8372 as a Mass Storage device and not (somehow) as a modem. First, make sure you have the exace same device we're talking about. This can be confirmed by looking at two values using the following command (while the dongle is plugged in): As an elevated user:

    # lsusb | grep Huawei
@ozgun
ozgun / cards_controller.rb
Created December 9, 2015 16:53
Custom Rails Responder for Service Objects
class Dashboard::Payments::CardsController < ::Dashboard::Payments::BaseController
self.responder = Core::CustomServiceResponder
respond_to :html
before_action :customer_required
def destroy
service = Payments::Stripe::DeleteCreditCard.new(current_user)
status_object = service.call(params[:identifier])
@stereodenis
stereodenis / gist:d5749a0f17b1b53b5963
Last active August 10, 2021 17:00
social meta tags helper ruby on rails 4
def social_meta_tags
title = "#{(content_for?(:title) ? (strip_tags(content_for(:title)).html_safe + ' / ') : '')}#{t('project_title')}"
description = content_for?(:description) ? content_for(:description) : ''
image = if @doc.present?
image_url(@doc.cover_photo.cover.url)
elsif @main.present?
image_url(@main.cover_photo.cover.url)
else
''
end