Last active
August 29, 2015 14:18
-
-
Save thomasklemm/d1788a5102de7658f6a7 to your computer and use it in GitHub Desktop.
ActiveRecord .sorted_where scope
This file contains hidden or 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
ActiveRecord::Base.class_eval do | |
def self.sorted_where(**options) | |
# Sort records by the first field given | |
sort_field, ordered_values = options.first[0], options.first[1] | |
values_and_positions = ordered_values.map.with_index { |id, index| [id, index] } | |
positions_by_value = Hash[*values_and_positions.flatten] | |
where(**options).to_a.sort_by do |record| | |
positions_by_value[record.public_send(sort_field)] | |
end | |
end | |
end | |
This file contains hidden or 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
require 'spec_helper' | |
describe ActiveRecord::Base do | |
describe '.sorted_where' do | |
ALPHABET = ('a'..'z').to_a | |
ALPHABET.each do |char| | |
let!(char.to_sym) do | |
# Works on all ActiveRecord models, Facebook profiles are just an easy example here | |
create(:facebook_profile, handle: char) | |
end | |
end | |
it 'returns the records sorted by the first item of the given conditions' do | |
sorted_handles = %w[a z y b d f r t s c] | |
records = FacebookProfile.sorted_where(handle: sorted_handles) | |
records.map(&:handle).should == sorted_handles | |
end | |
it 'handles records that cannot be found' do | |
sorted_handles = %w[a z b MISSING HANDLES c t s] | |
expected_handles = %w[a z b c t s] | |
records = FacebookProfile.sorted_where(handle: sorted_handles) | |
records.map(&:handle).should == expected_handles | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment