Skip to content

Instantly share code, notes, and snippets.

@jenny-codes
jenny-codes / activerecord_includes_preload_eager_load_query.rb
Last active February 19, 2019 04:25
A look at the differences of query outputs between :includes, :preload, :eager_load methods provided by Rails' ActiveRecord
# ActiveRecord::Base.logger = Logger.new(STDOUT)
Speaker.count # 1873
Talk.count # 1576
Speaker.includes(:talks).to_a
# SELECT `speakers`.* FROM `speakers`
# SELECT `talks`.* FROM `talks` WHERE `talks`.`speaker_id` IN (1, 2, 3,...(omitted)
Speaker.preload(:talks).to_a
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :ensure_domain
private
def ensure_domain
if request.env['HTTP_HOST'] == "jennycodes.herokuapp.com"
redirect_to "https://jennycodes.me#{request.env['REQUEST_PATH']}", status: 301
end
end
# source: https://openhome.cc/Gossip/Ruby/Proc.html
# https://openhome.cc/Gossip/Ruby/IteratorBlock.html
# https://tonytonyjan.net/2011/08/12/ruby-block-proc-lambda/
# self-built reduce function
class Array
def my_reduce(value = 0)
for i in 0...self.length
value = yield(value, self[i])
end
# source: http://blog.nicksieger.com/articles/2006/09/06/rubys-exception-hierarchy/
exceptions = []
tree = {}
ObjectSpace.each_object(Class) do |cls|
next unless cls.ancestors.include? Exception
next if exceptions.include? cls
next if cls.superclass == SystemCallError # avoid dumping Errno's
exceptions << cls
cls.ancestors.delete_if {|e| [Object, Kernel].include? e }.reverse.inject(tree) {|memo,cls| memo[cls] ||= {}}
# Error module to Handle errors globally
# include Error::ErrorHandler in application_controller.rb
module Error
module ErrorHandler
def self.included(clazz)
clazz.class_eval do
rescue_from StandardError, with: :standard_error
end
end
# Let f(N) be the number of 8s that occur when you write out all the numbers from 1 to N.
# For example:
# f(6) = 0
# f(8) = 1
# f(20) = 2
# f(80) = 9
# f(100) = 20
def f(N)
base = []