Last active
August 27, 2015 00:52
-
-
Save kbrock/f6ad14b68ed625e6f748 to your computer and use it in GitHub Desktop.
Testing different ways to bring back active records by the source ids
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'ostruct' | |
require 'byebug' | |
module Enumerable | |
def index_by | |
if block_given? | |
Hash[map { |elem| [yield(elem), elem] }] | |
else | |
to_enum(:index_by) { size if respond_to?(:size) } | |
end | |
end | |
end | |
class St | |
attr_accessor :id | |
def initialize(id) | |
self.id = id | |
end | |
end | |
class Model | |
def self.where(opts) | |
opts[:id].map(&:to_i).sort.map { |id| St.new(id) } | |
end | |
end | |
ids = ["1","4","5","3","22", "11", "8"] | |
puts ids.map(&:to_i).inspect | |
# ==> [1, 4, 5, 3, 22, 11, 8] | |
recs = Model.where(:id => ids).index_by(&:id) | |
ret = ids.map { |id| recs[id.to_i] } | |
puts ret.map(&:id).inspect | |
# ==> [1, 4, 5, 3, 22, 11, 8] | |
#ret = Model.where(:id => ids).sort_by.with_index { |e, i| puts "#{i}: #{e.id} => #{ids[i]}" ; ids[i] } | |
# | |
#puts ret.map(&:id).inspect | |
# # ==> [1, 11, 8, 5, 3, 4, 22] | |
ret = Model.where(:id => ids).sort_by.with_index { |e, i| ids.index(e.id.to_s) } | |
puts ret.map(&:id).inspect | |
# ==> [1, 4, 5, 3, 22, 11, 8] | |
id_i = ids.each_with_object({}).with_index { |(id, h), i| h[id.to_i] = i } | |
ret = Model.where(:id => ids).sort_by { |e| id_i[e.id] } | |
puts ret.map(&:id).inspect | |
# ==> [1, 4, 5, 3, 22, 11, 8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment