Skip to content

Instantly share code, notes, and snippets.

# 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 = []
# 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
# 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] ||= {}}
# 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
# 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
@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
@jenny-codes
jenny-codes / activerecord_joins_usage.rb
Last active February 19, 2019 04:41
Examples of when to use :joins provided by Rails' ActiveRecord
# Speaker -> Talks
# CORRECT USAGE
# Select speakers that have one or more talks and returns all attributes (columns) plus talk's title.
Speaker.joins(:talks).select('distinct speakers.*, talks.title as talks_title').to_a
# SELECT distinct speakers.*, talks.title as talks_title FROM `speakers` INNER JOIN `talks` ON `talks`.`speaker_id` = `speakers`.`id`
# Select speaker whose associated talk(s) is at status 5.
Speaker.joins(:talks).where(talks: {status: 5})
# SELECT `speakers`.* FROM `speakers` INNER JOIN `talks` ON `talks`.`speaker_id` = `speakers`.`id` WHERE `talks`.`status` = 5
@jenny-codes
jenny-codes / ruby_benchmark_usage.rb
Last active February 19, 2019 05:50
Benchmarking performances between :preload, :eager_load, :includes
require 'benchmark/ips'
def test
Benchmark.ips do |bm|
bm.report('#preload ') do
Speaker.preload(:talks).to_a
end
bm.report('#eager_load') do
Speaker.eager_load(:talks).to_a
@jenny-codes
jenny-codes / ruby_gil_threads_test.rb
Created March 5, 2019 13:14
At database querying the GIL is released.
require 'thwait'
require 'pg'
start = Time.now
first_sleep = Thread.new do
puts 'Starting sleep 1'
conn = PG::Connection.open(dbname: 'test')
conn.exec('SELECT pg_sleep(1);')
puts 'Finished sleep 1'
@jenny-codes
jenny-codes / ruby_gil_mutex.rb
Last active March 5, 2019 13:34
Use Mutex to avoid involuntary context switch in Ruby.
def send_money(amount)
puts "Sending $#{amount}"
sleep 1 # Simulate network call sending of money
end
lock = Mutex.new
threads = []
money_is_sent = false
2.times do