Skip to content

Instantly share code, notes, and snippets.

View dvandersluis's full-sized avatar

Daniel Vandersluis dvandersluis

View GitHub Profile
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "rails", '6.0.3'
@dvandersluis
dvandersluis / 1 - benchmark.rb
Last active November 23, 2018 16:51
Fixing ActiveRecord_Relation#pluck vs map
require 'benchmark/ips'
collection = User.limit(1)
module ActiveRecord
module Calculations
alias_method :old_pluck, :pluck
# original: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation/calculations.rb#L184-L201
def pluck(*column_names)
@dvandersluis
dvandersluis / 1 - benchmark.rb
Last active November 23, 2018 16:29
Rails attribute lookup
require 'benchmark/ips'
user = User.last
Benchmark.ips do |x|
x.report('.attr') { user.name }
x.report('[attr]') { user.[]('name') }
# What rails calls for user['name']
x.report('read_attr/missing') { user.read_attribute('name') { |n| missing_attribute(n, caller) } }
@dvandersluis
dvandersluis / 1 - benchmark.rb
Last active November 23, 2018 04:39
Map vs Pluck on a collection of ActiveRecords
require 'benchmark/ips'
photo = Photo.last
arr = [photo]
Benchmark.ips do |x|
x.report('map') { arr.map(&:id) }
x.report('pluck') { arr.pluck(:id) }
x.compare!
end
source 'https://rubygems.org'
gemspec
group :development do
gem 'rubocop_defaults', git: 'https://github.com/dvandersluis/rubocop_defaults.git'
end
source 'https://rubygems.org'
# Specify your gem's dependencies in my_gem.gemspec
gemspec
def gemspec(opts = nil)
opts ||= {}
path = opts[:path] || "."
glob = opts[:glob]
name = opts[:name]
development_group = opts[:development_group] || :development
expanded_path = gemfile_root.join(path)
gemspecs = Dir[File.join(expanded_path, "{,*}.gemspec")].map {|g| Bundler.load_gemspec(g) }.compact
gemspecs.reject! {|s| s.name != name } if name
@dvandersluis
dvandersluis / 1 - overridable_alias.rb
Last active May 25, 2017 15:35
Possible solution to the alias puzzle, with benchmarks
require 'active_support/core_ext/array/wrap'
module OverridableAlias
def overridable_alias(name, aliases:, &block)
define_method(name) do
method = method(name)
if method.super_method
send(name) # faster than method.call
else
class A
def foo
'hello'
end
alias_method :bar, :foo
end
class B < A
def foo
# See http://stackoverflow.com/questions/1987354/how-to-set-locale-default-url-options-for-functional-tests-rails/8920258#8920258
class ActionController::TestCase
module Behavior
def process_with_default_locale(action, parameters = nil, session = nil, flash = nil, http_method = 'GET')
parameters = { :locale => "en" }.merge( parameters || {} )
process_without_default_locale(action, parameters, session, flash, http_method)
end
alias_method_chain :process, :default_locale
end
end