Skip to content

Instantly share code, notes, and snippets.

View yuki24's full-sized avatar
🔢
NaN :trollface:

Yuki Nishijima yuki24

🔢
NaN :trollface:
View GitHub Profile
@yuki24
yuki24 / null_user.rb
Created April 8, 2014 01:59
NullUser written in meta-programming
class NullUser
User.reflections.each do |key, value|
name = key.to_s
if value.collection?
eval <<-RUBY
def #{name}
#{value.klass}.none
end
@yuki24
yuki24 / error_pages.rb
Last active August 29, 2015 13:58
Idea for simple and dynamic error page.
class ErrorPages < Ambulance::App
# idea 0: rails' rescue_from
rescue_from CanCan::AccessDenied, ActiveRecord::NotFound, ActionController::RoutingError do |exception|
render file: 'public/404.html', status: :not_found, layout: false
end
# idea 1:
routes ActiveRecord::NotFound,
ActionController::RoutingError, to: 404
@yuki24
yuki24 / application.rb
Last active August 29, 2015 14:01
Error handler that generates error pages dynamically in Rails
# config/application.rb
config.exceptions_app = ->(env) { ErrorsController.action(:show).call(env) }
@yuki24
yuki24 / git_diff_by_commit_messages.sh
Created June 1, 2014 22:47
git diff by commit messages
BRANCH=0.16-stable; M=`git log --pretty=format:'%s' master | sort`; B=`git log --pretty=format:'%s' $BRANCH | sort`; diff <(echo "${MASTER}") <(echo "${B}") | grep "^>"
@yuki24
yuki24 / base_notifier.rb
Last active August 29, 2015 14:07
Active Push API example
class BaseNotifier < ActivePush::Base
self.notifier_name = "base_notifier"
default gcm: {collapse_key: '...', delay_while_idle: false},
wp: {
message_id: 'message id',
notification_class: 'notification class',
windowsphone_target: 'target'
}
@yuki24
yuki24 / application_controller.rb
Created November 27, 2014 17:23
Force-return a JSON response. Always.
class ApplicationController < ActionController::Base
before_filter :override_request_formats
def override_request_formats
request.formats = [:json]
end
...
end
@yuki24
yuki24 / array_max_vs_if.rb
Last active August 29, 2015 14:11
Array#max vs if
require 'benchmark/ips'
Benchmark.ips do |x|
NEGATIVE = "-1"
ZERO = "0"
ONE = "1"
TWO = "2"
x.report("Array#max ( -1)") { [NEGATIVE.to_i, 1].max - 1 }
x.report("Array#max ( 0)") { [ ZERO.to_i, 1].max - 1 }
@yuki24
yuki24 / array_to_proc.rb
Created January 1, 2015 16:37
Array#to_proc
class Array
def to_proc
->(obj) { obj[first] }
end unless method_defined?(:to_proc)
end
users = [
{name: "Matz"},
{name: "DHH"},
{name: "Yuki"}
require 'benchmark/ips'
Benchmark.ips do |x|
x.report "nothing" do
[1, 2, 3]
end
x.report "#-" do
[1, 2, 3] - [3]
end
@yuki24
yuki24 / each_char_vs_each_codepoint.txt
Last active August 29, 2015 14:18
Levenshtein benchmark
Calculating -------------------------------------
each_char 924.000 i/100ms
each_codepoint 1.381k i/100ms
-------------------------------------------------
each_char 9.320k (± 5.1%) i/s - 47.124k
each_codepoint 13.857k (± 3.6%) i/s - 70.431k
Comparison:
each_codepoint: 13857.4 i/s
each_char: 9319.5 i/s - 1.49x slower