Skip to content

Instantly share code, notes, and snippets.

@Malet
Malet / double_user_balance_migration.rb
Last active August 29, 2015 14:24
Future-proof Ruby on Rails migrations
class DoubleUserBalance < ActiveRecord::Migration
def up
# Double user's balance
prepared = ActiveRecord::Base.connection.raw_connection.prepare("
UPDATE users
SET balance = balance * ?
")
prepared.execute(2)
prepared.close
end
@Malet
Malet / hash.stringify_keys.rb
Created August 23, 2015 13:40
Hash Stringify Keys
class Hash
def stringify_keys
result = {}
each_key do |key|
result[key.to_s] = if self[key].class == Hash
self[key].stringify_keys
else
self[key]
end
end
@Malet
Malet / tputs.rb
Created October 13, 2015 09:24
Threadsafe puts
def tputs(*params)
$io_lock ||= Mutex.new
$io_lock.synchronize{ puts(*params) }
end
@Malet
Malet / to_utf8.rb
Last active December 31, 2015 05:49
Prevent invalid UTF-8 byte sequences for Ruby 2.0 / 2.1 (1.9 untested)
class String
REPLACE_INVALID_WITH = '�'
def to_utf8
self.encode('utf-8', invalid: :replace, undef: :replace, replace: REPLACE_INVALID_WITH).
chars.map{ |i| i.valid_encoding? ? i : REPLACE_INVALID_WITH }.join
end
end
@Malet
Malet / thread_pool.rb
Created October 13, 2015 09:16
ThreadPool
class ThreadPool
def initialize(input_array:, callback:, threads: 128)
@callback, @input_array, @threads = callback, input_array, threads
end
def run
results = []
input_queue, results_queue = Queue.new, Queue.new
@input_array.each{ |item| input_queue << item }