Skip to content

Instantly share code, notes, and snippets.

View tsaito-cyber's full-sized avatar

tsaito-cyber tsaito-cyber

View GitHub Profile
@tsaito-cyber
tsaito-cyber / validatable.rb
Created May 12, 2020 14:13
validatable.rb
module Validatable
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def validate(attribute, &block)
attr_accessor attribute unless defined?(attribute)
alias_method "#{attribute}_orig=", "#{attribute}="
define_method("#{attribute}=") do |val|
self.__send__("#{attribute}_orig=", val) if block.(val)
@tsaito-cyber
tsaito-cyber / 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
@tsaito-cyber
tsaito-cyber / 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)
@tsaito-cyber
tsaito-cyber / 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
@tsaito-cyber
tsaito-cyber / 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
@tsaito-cyber
tsaito-cyber / 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
@tsaito-cyber
tsaito-cyber / 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
@tsaito-cyber
tsaito-cyber / Gemfile
Last active May 2, 2020 13:31
worker_get_url.rb
source 'https://rubygems.org'
gem 'open_uri_redirections'