Skip to content

Instantly share code, notes, and snippets.

View YanhaoYang's full-sized avatar

Yanhao Yang YanhaoYang

  • Berlin, Germany
View GitHub Profile
@YanhaoYang
YanhaoYang / nested-structs-to-json.go
Created February 6, 2017 08:11
Golang: json.Marshal for nested structs
package main
import (
"fmt"
"encoding/json"
)
type A struct {
A string
}
@YanhaoYang
YanhaoYang / close_channel.go
Created February 2, 2017 07:40
Ensure channel is closed, but not close it twice
done := make(chan struct{})
defer func(c chan struct{}) {
select {
case <-c:
default:
close(c)
}
}(done)
@YanhaoYang
YanhaoYang / monkey-patch-by-prepend.rb
Created May 21, 2016 13:04
Monkey patch by prepend
class A
def hi
puts 'hi'
end
end
a = A.new
a.hi
# => "hi"
@YanhaoYang
YanhaoYang / monkey-patch-by-alias_method.rb
Last active May 21, 2016 09:21
Monkey patch by alias_method
class A
def hi
puts "hi"
end
end
a = A.new
a.hi
# => hi
@YanhaoYang
YanhaoYang / redefine-a-method-in-a-module.rb
Created May 21, 2016 08:42
Redefine a method in a module
module M1
def hi
puts "hi in M1"
end
end
class A
include M1
def ha
@YanhaoYang
YanhaoYang / redefine-a-method-by-opening-the-class.rb
Last active May 21, 2016 08:44
Redefine a method by opening the class
class A
def hi
puts 'hi'
end
end
a = A.new
a.hi
# => "hi"
@YanhaoYang
YanhaoYang / rdoc-example.rb
Created November 17, 2015 14:41 — forked from nicholasjhenry/rdoc-example.rb
RDoc Example
# * Style guide based on Rails documention
module Namespace #:nodoc: don't document this
# Generic Namespace exception class
class NamespaceError < StandardError
end
# Raised when...
class SpecificError < NamespaceError
end
@YanhaoYang
YanhaoYang / parse-rails-log.rb
Last active August 29, 2015 14:16
Parse rails log and generate structured data
require "json"
requests = {}
File.open("production.log").each_line do |ln|
if ln =~ /^\[([0-9a-f]+)\] (.+)/
id = $1
msg = $2
requests[id] ||= {lines: []}
requests[id][:lines] << msg
if msg =~ /Processing by (.+) as/
@YanhaoYang
YanhaoYang / cache-get-requests-of-activeresource.rb
Created January 10, 2015 15:06
Cache GET requests of ActiveResource
module ArCache
extend ActiveSupport::Concern
def get(path, headers = {})
cache_key = "ar_cache_#{path}"
Rails.cache.fetch(cache_key, expires_in: 60.seconds) do
super
end
end
@YanhaoYang
YanhaoYang / load-redis-session-in-console.rb
Created December 9, 2014 14:03
Load Rails' session data from redis in console
YourApp::Application.config.session_store.new(app).get_session({}, "session_store:fe95d1b2921ebf2eb7f18ece4f588520")