Skip to content

Instantly share code, notes, and snippets.

@tompave
tompave / actors_and_messages.rb
Created Nov 10, 2018
Actors and Messages in Ruby
View actors_and_messages.rb
require "colorize"
REGISTRY = {}
DEBUG = false
SLEEP = 0.5
def register(id)
mailbox = Queue.new
Thread.current[:process_id] = id
REGISTRY[id] = mailbox
@tompave
tompave / thread_memory_overhead.rb
Created Mar 14, 2018
Find the memory overhead of threads in Ruby
View thread_memory_overhead.rb
def memory_kb
`ps -o rss= -p #{Process.pid}`.chomp.to_i
end
MEM_LOG = "current memory: %{mem} kB (+%{incr})".freeze
THR_LOG = "New Thread!".freeze
current_mem = 0
loop do
m = memory_kb()
@tompave
tompave / timing.exs
Last active Aug 20, 2016
Fun with Elixir macros and Streams
View timing.exs
defmodule Timing do
def now do
:os.system_time(:milli_seconds)
end
# broken! the block is executed immediately
#
def ftime([do: block]) do
t0 = now
{ :ok, block, now - t0 }
@tompave
tompave / middleman_build.sh
Last active May 30, 2016
Build a Middleman site and commit it to an orphan master branch, see the related blog post for the setup: http://tommaso.pavese.me/2016/05/22/how-to-deploy-a-middleman-website-to-github-pages/
View middleman_build.sh
#!/bin/bash
middleman build &&
echo "--- middleman build complete"
git checkout master &&
echo "--- cleaning old build"
(ls -1 | grep -v 'build' | xargs rm -rf ) &&
View totp_qr_code_generation.rb
require 'digest/md5'
require 'base32'
require 'rqrcode'
require 'rotp'
def print_as_qr(string)
qrcode = RQRCode::QRCode.new(string)
filename = File.expand_path "~/Desktop/qr_#{rand(10_000)}.png"
qrcode.as_png.save(filename, :fast_rgb)
end
@tompave
tompave / closures.rb
Created Dec 16, 2015
closures in Ruby
View closures.rb
i = 1000
f1 = Proc.new { |x| x * x }
f2 = -> (func, int) { puts "the result is: '#{func.call(int)}', i is: '#{i}'" }
def run(range, operation, printer)
range.each do |i|
printer.call(operation, i)
end
end
@tompave
tompave / percent_encoding_guard.rb
Last active Aug 29, 2015
Rack middleware guards
View percent_encoding_guard.rb
# Issue on github:
# https://github.com/rack/rack/issues/337
#
# Possible patch:
# https://gist.github.com/psychocandy/3130349
# but I don't like the idea of monkeypatching the standard library
#
# Rack middleware:
# http://stackoverflow.com/questions/16269897/rails-argumenterror-invalid-encoding
#
View risotto.md

Risotto for 4 people

Ingredients

  • rice (type: Carnaroli or Arborio)

    • 80-100 g per person, total: ~400 g
    • a bit more if you're hungry
  • one onion

View try_chain.rb
require 'active_support/core_ext/object/try'
module TryChain
def try_chain
@proxy = Proxy.new(self)
end
class Proxy
@tompave
tompave / impersonation_utilities.rb
Last active Aug 29, 2015
Poor Man's cross-authentication
View impersonation_utilities.rb
# impersonation_utilities.rb
require 'digest/md5'
module ImpersonationUtilities
SHARED_SECRET = "I'm a secret string!"
TOKEN_VALID_FOR_DAYS = 1
class << self