Skip to content

Instantly share code, notes, and snippets.

View ifyouseewendy's full-sized avatar

Di Wen ifyouseewendy

View GitHub Profile
Note 1.
Single Table Inheritance
http://api.rubyonrails.org/classes/ActiveRecord/Base.html
class Teacher < User
has_many :courses
end
class Course
DATES = ["2012-01-01",
"2012-02-01",
"2012-03-01",
"2012-04-01",
"2012-05-01",
"2012-06-01",
"2012-07-01",
"2012-08-01",
"2012-09-01",
"2012-10-01",
#!/usr/bin/env ruby
require 'rubygems'
require 'gattica'
# Login
ga = Gattica.new({
:email => '',
:password => ''
})
#!/usr/bin/env ruby
# encoding: utf-8
# ======================================================
# <N+1 problem>
#
# Post.all.each do |p|
# puts p.category.name
# end
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'arel', github: 'rails/arel'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
@ifyouseewendy
ifyouseewendy / n+1_benchmark_mongoid.rb
Created May 8, 2014 11:43
by latest two versions, '4.0.0.beta1' behaves much better than '3.1.6'
#!/usr/bin/env ruby
# encoding: utf-8
# ======================================================
# <N+1 problem>
#
# Post.all.each do |p|
# puts p.category.name
# end
@ifyouseewendy
ifyouseewendy / isolate_dynamic_receptor.rb
Created May 8, 2014 11:50
Use a class whose sole responsibility is to handle the method_missing cases.
# Despite the added complexity, method_missing is a powerful tool that needs to be used when the interface of a class cannot be predetermined.
# Use Isolate Dynamic Receptor to move the method_missing behavior to a new class: a class whose sole responsibility is to handle the method_missing cases.
class MessageCollector
instance_methods.each do |meth|
undef_method meth unless meth =~ /^(__|inspect)/
end
def messages
@messages ||= []
@ifyouseewendy
ifyouseewendy / replace_dynamic_receptor_with_dynamic_method_definition.rb
Created May 8, 2014 11:51
Replace `method_missing` with dynamic method definition.
class Decorator
def initialize(subject)
@subject = subject
end
def method_missing(sym, *args, &block)
@subject.send sym, *args, &block
end
end
@ifyouseewendy
ifyouseewendy / introduce_class_annotation.rb
Created May 8, 2014 11:52
You have a method whose implementation steps are so common that they can safely be hidden away.
module CustomInitializers
def hash_initializer(*attribute_names)
define_method(:initialize) do |*args|
data = args.first
attribute_names.each do |attr|
instance_variable_set "@#{attr}", data[attr]
end
end
self.class_eval do
#!/usr/bin/env ruby
require 'mongoid'
require 'mongoid/support/query_counter'
Mongoid.configure.connect_to("mongoid_test")
def count_queries(&block)
query_counter = Mongoid::QueryCounter.new
query_counter.instrument(&block)