Skip to content

Instantly share code, notes, and snippets.

@Erol
Created July 11, 2013 01:22
Show Gist options
  • Save Erol/5971754 to your computer and use it in GitHub Desktop.
Save Erol/5971754 to your computer and use it in GitHub Desktop.
Make selecting or rejecting items from an Ohm collection faster by getting only selected fields.
require 'benchmark'
User.all.size
#=> 30000
# BEFORE
Benchmark.measure { User.all.select { |user| user.firstname =~ /Erol/ } }
#=> 66.630000 1.070000 67.700000 ( 67.868905)
# AFTER
Benchmark.measure { User.all.select(:firstname) { |firstname| firstname =~ /Erol/ } }
#=> 2.080000 0.020000 2.100000 ( 2.231251)
module Ohm::Collection
def select(*atts)
return Enumerator.new(self, :select, *atts) unless block_given?
return super if atts.empty?
ids = key.sort(by: '#', get: ['#'] + atts.map { |att| "#{model.key}:*->#{att}" })
.select { |values| yield *values.slice(1..-1) }
.map { |values| values[0] }
fetch ids
end
def reject(*atts)
return Enumerator.new(self, :select, *atts) unless block_given?
return super if atts.empty?
ids = key.sort(by: '#', get: ['#'] + atts.map { |att| "#{model.key}:*->#{att}" })
.reject { |values| yield *values.slice(1..-1) }
.map { |values| values[0] }
fetch ids
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment