Skip to content

Instantly share code, notes, and snippets.

Malet

Block or report user

Report or block Malet

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
@Malet
Malet / tputs.rb
Created Oct 13, 2015
Threadsafe puts
View tputs.rb
def tputs(*params)
$io_lock ||= Mutex.new
$io_lock.synchronize{ puts(*params) }
end
View thread_pool.rb
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 }
View hash.stringify_keys.rb
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 / double_user_balance_migration.rb
Last active Aug 29, 2015
Future-proof Ruby on Rails migrations
View double_user_balance_migration.rb
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 / to_utf8.rb
Last active Dec 31, 2015
Prevent invalid UTF-8 byte sequences for Ruby 2.0 / 2.1 (1.9 untested)
View to_utf8.rb
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
You can’t perform that action at this time.