Skip to content

Instantly share code, notes, and snippets.

View amatsuda's full-sized avatar

Akira Matsuda amatsuda

View GitHub Profile
S = 'foo'
class A
def a() S; end
end
class B < BasicObject
# needs to be ::S
def b() ::S; end
end
@amatsuda
amatsuda / lvar.rb
Last active December 20, 2015 16:29
if false
a = 1
end
p a
#=> nil
p b
#=> undefined local variable or method `b' for main:Object (NameError)
Kernel.class_eval do
#FIXME this is terrible
def static(meth)
define_singleton_method(meth) do |*args, &b|
new.send meth, *args, &b
end
meth
end
def abstract(meth)
@amatsuda
amatsuda / database_cleaner_bench.rb
Last active December 23, 2015 06:29
Want to know how much time you're spending for cleaning database before and after each test?
# put this piece of code in your spec/spec_helper.rb or spec/support/any_rb_file.rb
# then run `rake spec`
module CleanerBench
def clean(*)
now = Time.now
super
@time_spent ||= 0
@time_spent += Time.now - now
end
+----------------------+--------+--------+---------+---------+-----+-------+
| Name | Lines | LOC | Classes | Methods | M/C | LOC/M |
+----------------------+--------+--------+---------+---------+-----+-------+
| Controllers | 48726 | 39215 | 522 | 3970 | 7 | 7 |
| Helpers | 14795 | 12125 | 15 | 1399 | 93 | 6 |
| Models | 96678 | 76140 | 1747 | 8548 | 4 | 6 |
| Mailers | 2208 | 1766 | 44 | 206 | 4 | 6 |
| Workers | 639 | 540 | 20 | 31 | 1 | 15 |
| Chanko units | 11713 | 9644 | 6 | 247 | 41 | 37 |
| Libraries | 50409 | 41650 | 592 | 3741 | 6 | 9 |
@amatsuda
amatsuda / shadowing_outer_local_variable.rb
Last active August 29, 2015 14:25
I do understand what's happening, but...
if false
a = 2
p a
else
Proc.new do |a|
p a
end
end
% rails g model m `ruby -e "801.times {|i| print %(c#{i} )}"` && rake db:migrate
% rails r 'p M.new.methods.length'
#=> 10000
@amatsuda
amatsuda / t.rb
Last active July 13, 2016 01:04
What happens when you def translate in IRB
def b() binding; end
eval 'def translate() end', b
eval '1'
# => t.rb:3:in `eval': wrong number of arguments (given 1, expected 0) (ArgumentError)
require 'benchmark/ips'
require 'json'
require 'oj'
require 'multi_json'
Benchmark.ips do |x|
hash = 100.times.inject(Hash.new) {|h, i| h["key#{i}"] = i; h}
x.report('to_json') do
hash.to_json
end
# Question: which module would raise an error?
module I
include
end
module P
prepend
end