Skip to content

Instantly share code, notes, and snippets.

View takuma-saito's full-sized avatar

takuma.saito takuma-saito

  • 13:12 (UTC +09:00)
View GitHub Profile
@takuma-saito
takuma-saito / delegatable.rb
Created May 12, 2020 13:44
delegatable.rb
module Delegatable
def self.included(base)
base.class_eval do
def self.delegate_method(method, to)
define_method(method) do |*args|
instance_variable_get(to).__send__(method, *args)
end
end
end
end
class String
def underscore
self.scan(/[A-Z][a-z]+/).map { |name| name.tr('A-Z', 'a-z') }.join("_")
end
end
class Crumb
def initialize(mgr, &block)
@mgr = mgr
@block = block
end
@takuma-saito
takuma-saito / gmail_search.rb
Created May 3, 2020 15:49
Gmail の検索条件を ruby の DSL で扱えるようにした
class Gmail
def initialize(&block)
@block = block
@items = []
end
def run
self.instance_eval(&@block)
@items.join(" ")
end
def cond(condition, &block)
@takuma-saito
takuma-saito / main.rb
Created May 3, 2020 07:13
覆面算(汎用版)
# 問題:
# http://hidesugar.web.fc2.com/ym2/ym2musikuizan2.txt
# ABCDEF * G = FABCDE
# 解答: 230769 * 4 = 923076
def solve(sx, sy, sz, mapping)
x = sx.inject(0) {|sum, x| sum * 10 + mapping[x]}
y = sy.inject(0) {|sum, y| sum * 10 + mapping[y]}
z = Enumerator.new do |e|
t = (x * y)
class Future
def initialize(&block)
@que = Queue.new
@t = Thread.new {
@que << block.call
}
end
def value
return @que.pop
ensure
@takuma-saito
takuma-saito / connection_pool.rb
Last active May 3, 2020 10:32
connection_pool.rb
class ConnectionPool
attr_reader :conns
def initialize(max, &block)
@mutex = Mutex.new # マルチスレッドからの排他的ロック
@cv = ConditionVariable.new
@max = max
@que = []
@conns = []
@create_block = block
@created = 0
@takuma-saito
takuma-saito / has_secure_password.rb
Last active May 3, 2020 12:49
has_secure_password.rb
require 'digest/md5'
module SecurablePassword
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def has_secure_password(name = :password)
include HasSecurePassword.new(name)
end
@takuma-saito
takuma-saito / pubsub.rb
Last active May 3, 2020 04:14
pubsub.rb
class Topic
attr_reader :name
def initialize(name)
@name = name
@clients = {}
end
def publish(message)
@clients.values.each {|client| client.receive(@name, message)}
end
@takuma-saito
takuma-saito / Gemfile
Last active May 2, 2020 13:31
worker_get_url.rb
source 'https://rubygems.org'
gem 'open_uri_redirections'
require 'thread'
class Workers
def initialize(count)
@q = Queue.new
@count = count
@jobs = (0...@count).map.with_index {|id|
Thread.new do
while (job = @q.pop)
total = job.(id, total)