Skip to content

Instantly share code, notes, and snippets.

@thiagofm
thiagofm / pattern_matching_type.rb
Created September 4, 2022 08:43
Ruby Pattern Matching on Type
# Ruby pattern matching based on Type (=> operator)
[1,2,3] => [1, Integer, my_variable]
# This means:
# We want to assign `my_variable` (variable binding),
# but only if the first position is 1 and second position is an Integer)
my_variable # => 3 ✨
# What if it doesn't match? You get an exception 💣
[1,2,3] => [Integer, String, my_variable]
# [1, 2, 3]: String === 2 does not return true (NoMatchingPatternError)
# sudo vi /etc/nginx/sites-enabled/unicorn.qna.conf
# это директива nginx которая указывает список бэкенд серверов которые физически будут обрабатывать запрос и таким образом nginx будет проксировать запросы к указанным серверам и даже как loadbalancer
upstream unicorn {
server unix:/home/deployer/qna/shared/tmp/sockets/unicorn.qna.sock fail_timeout=0; # описали сервер ссылающийся на сокет а можно было на ip и таких серверов может быть несколько, fail_timeout - означает что nginx не будет посылать запросы если наш сервер не отвечает
}
# к этому никакого отношения upstream не имеет
server {
listen 80;
@shilovk
shilovk / qna_backup.rb
Last active August 19, 2020 15:27
backup to Yandex Object Storage
# ...
store_with S3 do |s3|
s3.access_key_id = "your_key"
s3.secret_access_key = "your_pass"
s3.bucket = "your_bucket_name"
s3.path = "your_path_to_backup"
s3.region = "ru-central1"
s3.fog_options = { endpoint: "https://storage.yandexcloud.net" }
end
@bazzel
bazzel / README.md
Last active May 26, 2021 04:20
Rails 6 and Bootstrap 4

This blogpost shows how to setup Rails 6 with Bootstrap 4.

This snippet shows a somehow different and less customized approach.

$ rails new rails6-bootstrap4
$ bundle --binstubs
$ yarn add bootstrap jquery popper.js expose-loader
@javier-menendez
javier-menendez / sqlite3_disable_referential_to_rails_5.rb
Last active July 11, 2024 22:33
Rails 5 initializer for disable foreign keys during `alter_table` for sqlite3 adapter
require 'active_record/connection_adapters/sqlite3_adapter'
#
# Monkey-patch for disable foreign keys during `alter_table` for sqlite3 adapter for Rails 5
#
module ActiveRecord
module ConnectionAdapters
class SQLite3Adapter < AbstractAdapter
@db0sch
db0sch / regenerate_credentials.md
Last active May 11, 2024 10:34
How to regenerate the master key for Rails 5.2 credentials

If your master.key has been compromised, you might want to regenerate it.

No key regeneration feature at the moment. We have to do it manually.

  1. Copy content of original credentials rails credentials:show somewhere temporarily.
  2. Remove config/master.key and config/credentials.yml.enc
  3. Run EDITOR=vim rails credentials:edit in the terminal: This command will create a new master.key and credentials.yml.enc if they do not exist.
  4. Paste the original credentials you copied (step 1) in the new credentials file (and save + quit vim)
  5. Add and Commit the file config/credentials.yml.enc
@satendra02
satendra02 / app.DockerFile
Last active July 12, 2024 02:39
docker+rails+puma+nginx+postgres (Production ready)
FROM ruby:2.3.1
# Install dependencies
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
# Set an environment variable where the Rails app is installed to inside of Docker image:
ENV RAILS_ROOT /var/www/app_name
RUN mkdir -p $RAILS_ROOT
# Set working directory, where the commands will be ran:
@neretin-trike
neretin-trike / pug.md
Last active June 20, 2024 07:31
Туториал по HTML препроцессору Pug (Jade)
@przbadu
przbadu / _vue-rails.md
Last active July 16, 2022 21:48
Vue js and Rails integration

Setup Rails and Vuejs

  1. Generate new rails app using --webpack flag
rails new myApp --webpack=vue

Note:

  1. You can use --webpack=angular for angular application and --webpack=react for react.
@fomvasss
fomvasss / Проектирование Rest API.txt
Last active March 22, 2024 19:13
Проектирование API.txt
Аббревиатура REST расшифровывается как representational state transfer — «передача состояния представления» или, лучше сказать, представление данных в удобном для клиента формате. Термин “REST” был введен Роем Филдингом в 2000 г. Основная идея REST в том, что каждое обращение к сервису переводит клиентское приложение в новое состояние. По сути, REST — не протокол и не стандарт, а подход, архитектурный стиль проектирования API.
Любой ресурс имеет ID, по которому можно получить данные.
Сервер не хранит состояние — это значит, сервер не отделяет один вызов от другого, не сохраняет все сессии в памяти.
Методы POST и PUT должны возвращать обратно объект, который они изменили или создали, — это позволит сократить время обращения к сервису вдвое.
Возвращайте соответствующие http коды статуса в каждом ответе. Успешные ответы должны содержать следующие коды:
200 — для GET запроса и для синхронных DETELE и PATCH
201 — для синхронного POST запроса
202 — для асинхронных POST, DELETE и PATCH запросов