Skip to content

Instantly share code, notes, and snippets.

@estum
estum / splat_struct.rb
Created December 3, 2014 20:23
Ruby's Struct subclass with splats support
#= SplatStruct
# `Struct` subclass with splats support
#
# SampleClass = SplatStruct.new(:a, :b, [:c]) do |klass|
# def avgc
# Rational(c.inject(:+), c.length).to_f
# end
# end
#
# object = SampleClass.new(1,2,3,4,5)
@estum
estum / pryew.sh
Created December 18, 2014 23:50
Pry Everywhere: shell command to run pry in the current context
#!/usr/bin/env bash
VERBOSE="false"
while getopts "v" flag; do
case "${flag}" in
v) VERBOSE="true" ;;
esac
done
readonly VERBOSE
@estum
estum / migrate_hstore_to_json.rb
Last active October 11, 2022 12:29
Ruby on Rails & Postgres: Reversible migrate hstore column to jsonb with contents
class MigrateHstoreToJson < ActiveRecord::Migration
def up
rename_column :posts, :data, :data_hstore
add_column :posts, :data, :jsonb, default: {}, null: false, index: { using: 'gin' }
execute 'UPDATE "posts" SET "data" = json_object(hstore_to_matrix("data_hstore"))::jsonb'
remove_column :posts, :data_hstore
end
def down
rename_column :posts, :data, :data_jsonb
@estum
estum / active_job_logging_hook.rb
Created January 21, 2015 11:14
Sidekiq + ActiveJob logging hook (fixing job class name in output log)
# lib/sidekiq/active_job_logging_hook.rb
require 'sidekiq/middleware/server/logging'
class Sidekiq::ActiveJobLoggingHook < Sidekiq::Middleware::Server::Logging
def call(worker, item, queue)
klass = item['args'].try(:first).try(:[], 'job_class').presence || worker.class.to_s
Sidekiq::Logging.with_context("#{klass} JID-#{item['job_id'] || item['jid']}") do
begin
@estum
estum / plutil.rb
Created January 29, 2015 16:10
Ruby "plutil" command class wrapper
require 'json'
class Plutil
module JSON
def self.load(plist)
Plutil.convert plist, to: :json do |converted_io|
::JSON.load(converted_io)
end
end
@estum
estum / has_many_limit_per_likes.rb
Last active August 29, 2015 14:15
Eager load has many polymorphic association with limit per each owner
# Standart behavior: if you eager load an association with a specified :limit option, it will be ignored, returning all the associated objects
# This example shows how to eager load limited number of records in collection.
# Usage:
# Post.find(42).likes.size # => 300
# Post.find(42).likes.limit_per_target(5).size # => 5
# Post.preload(:likes).map {|t| t.likes.size } # => [100, 200, 300, ... ]
# Post.preload(:limited_likes).map {|t| t.likes.size } # => [5, 5, 5, ... ]
#
# recommended: postgres ~>9.4, ruby ~>2.2, rails ~>4.2, squeel
@estum
estum / named_captures.rb
Created February 23, 2015 20:43
MatchData#named_captures: a hash of names and matches of captures
require "active_support/core_ext/hash/transform_values"
class MatchData
# Returns a hash containing the names and matches of captures or nil.
#
# A key of the hash is a name of the named captures. A value of the hash is a
# matched string or an array of corresponding matches.
#
# puts /(?<foo>.)(?<bar>.)(?<baz>.)(?<baz>.)/.match("hoge", &:named_captures).inspect
# # => {"foo"=>"h", "bar"=>"o", "baz"=>["g", "e"]}
@estum
estum / README.rdoc
Last active August 23, 2023 13:47
iTerm: Coprocess-script to auto-paste sudo password from keychain

iTerm Coprocess-script to auto-paste sudo password from keychain

Usage

  1. Open Keychain Access.app and create new object using the host as a name (“example.com”), username with sudo rights (“user”) and it’s password.

  2. Add a trigger for iTerm’s profile (‘Advanced‘ tab):

    • Regular Expression: \$ sudo

    • Action: Run Coprocess…

    • Parameters: /path/to/iterm_reply_with_keychain.rb [email protected]

@estum
estum / awesome_print_proc.rb
Created April 13, 2015 00:33
AwesomePrint::Proc: inspecting Proc instances with source code (using Sourcify)
# = Awesome Print Proc Formatter
#
# Prints source when inspecting Proc object.
# Requires <tt>sourcify (>= 0.6.0.rc4)</tt> gem.
begin
require "sourcify"
rescue LoadError
end
@estum
estum / array_to_proc.rb
Last active August 29, 2015 14:19
Array#to_proc: quick iterate chaining calls like .map(&[...])
unless Array.method_defined?(:to_proc)
class Array
# Converts array to proc with chained calls of items.
# Every item can be either a method name or an array with
# a method name and args.
#
# ==== Examples
#
# the_hash = { :one => "One", :two => "Two", :three => 3, :four => nil }
# mapping = { "one" => "1", "two" => "2", "" => "0" }