Skip to content

Instantly share code, notes, and snippets.

View godfat's full-sized avatar

Lin Jen-Shin (godfat) godfat

View GitHub Profile
require 'sequel'
module FasterSequelTimeParser # from activerecord
module_function
def parse string
string =~ /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
microsec = ($7.to_r * 1_000_000).to_i
::Time.utc($1.to_i, $2.to_i, $3.to_i, $4.to_i,
$5.to_i, $6.to_i, microsec)
end
net/http:
https://github.com/jnunemaker/httparty
https://github.com/rest-client/rest-client
https://github.com/lostisland/faraday
https://github.com/drbrain/net-http-persistent
ruby:
https://github.com/excon/excon
https://github.com/httprb/http
https://github.com/nahi/httpclient
Rails.application.config.after_initialize do
ActiveSupport.on_load(:active_record) do
oid = ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID
# https://github.com/rails/rails/blob/v4.2.3/activerecord/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb
oid::Jsonb = Class.new(oid::Json) do
def type
:jsonb
end
dataset_module do
# User.one_to_one(:auth)
# User.eager_cursor(1000, :auth) do |user|
# user.auth # no additional query
# end
def eager_cursor rows_per_fetch=1000, *associations
cursor = use_cursor(rows_per_fetch: rows_per_fetch)
cursor.each_slice(rows_per_fetch) do |records|
associations.each do |assoc|
refl = model.association_reflection(assoc)
@godfat
godfat / a.rb
Last active August 29, 2015 14:24
class User < Struct.new(:enable_email, :email)
extend Validator
validate :email, v.present(:enable_email) & v.match(:email, /[^@]+@[^@]+/)
end
User.new(true, 'a@b').check
@godfat
godfat / query.sql
Last active August 29, 2015 14:22
PostgreSQL fast random rows for tables with integer id with uniform distribution
WITH RECURSIVE results(id, i, picked, roll) AS (
WITH bounds AS (SELECT min(id), max(id) - min(id) AS delta FROM table)
(
SELECT NULL::integer
, 0
, ARRAY[]::integer[]
, min + round(delta * random())
FROM bounds
)
UNION ALL
class MigrateCookie < Struct.new(:app)
def call env
cookies = Rack::Utils.parse_query(env['HTTP_COOKIE'], ';,')
case cookies['_session_id']
when Array
status, headers, body = app.call(env)
headers['Set-Cookie'] =
"#{headers['Set-Cookie']}\n#{expire_old_session}"
[status, headers, body]
else
@godfat
godfat / api
Last active August 29, 2015 14:21
x-smtpapi: {"filters":{"templates":{"settings":{"enable":1,"template_id":"template-1"}}},
"section":{":name":"Alice",":message":"this is Bob."}}
html: <%template-2%>
"Lin Jen Shin (godfat) is a programmer who loves computer games, open source, Haskell and self-referential jokes, such as: %p=~/(.+)/;puts(($1%%$1)[/: (.+)/,1])"=~/(.+)/;puts(($1%$1)[/: (.+)/,1])
#!/bin/sh
echo RAILS_ENV={development,test} | xargs -n1 -P2 rake db:migrate
echo 'rake db:structure:dump,rake db:schema:dump' | xargs -d, -n1 -P2 sh -c
cp db/structure.sql db/schema.sql