diff --git a/lib/active_hash/relation.rb b/lib/active_hash/relation.rb index 90a7b50f..98dd7ef5 100644 --- a/lib/active_hash/relation.rb +++ b/lib/active_hash/relation.rb @@ -96,9 +96,7 @@ def order(*options) processed_args = preprocess_order_args(options) candidates = relation.dup - order_by_args!(candidates, processed_args) - - candidates + order_by_args(candidates, processed_args) end def to_ary @@ -179,7 +177,9 @@ def preprocess_order_args(order_args) ary.map! { |e| e.split(/\W+/) }.reverse! end - def order_by_args!(candidates, args) + def order_by_args(candidates, args) + ordered_candidates = [] + args.each do |arg| field, dir = if arg.is_a?(Hash) arg.to_a.flatten.map(&:to_sym) @@ -189,7 +189,7 @@ def order_by_args!(candidates, args) arg.to_sym end - candidates.sort! do |a, b| + ordered_candidates = candidates.sort do |a, b| if dir.present? && dir.to_sym.upcase.equal?(:DESC) b[field] <=> a[field] else @@ -197,6 +197,7 @@ def order_by_args!(candidates, args) end end end + ordered_candidates end end end diff --git a/spec/active_hash/base_spec.rb b/spec/active_hash/base_spec.rb index 3115bf7c..a4ecb7d7 100644 --- a/spec/active_hash/base_spec.rb +++ b/spec/active_hash/base_spec.rb @@ -992,6 +992,17 @@ class Region < ActiveHash::Base expect(countries.first).to eq Country.find_by(name: "Canada") expect(countries.second).to eq Country.find_by(name: "US") end + + it "doesn't change the order of original records" do + countries = Country.order(id: :desc) + expect(countries.first).to eq Country.find_by(name: "Mexico") + expect(countries.second).to eq Country.find_by(name: "Canada") + expect(countries.third).to eq Country.find_by(name: "US") + + expect(Country.all.first).to eq Country.find_by(name: "US") + expect(Country.all.second).to eq Country.find_by(name: "Canada") + expect(Country.all.third).to eq Country.find_by(name: "Mexico") + end end describe "#method_missing" do diff --git a/spec/active_hash/relation_spec.rb b/spec/active_hash/relation_spec.rb index f788bc42..e02d3dd0 100644 --- a/spec/active_hash/relation_spec.rb +++ b/spec/active_hash/relation_spec.rb @@ -50,4 +50,20 @@ expect(array.size).to eq(2) end end + + describe '#find' do + it 'returns a correct record' do + expect(subject.find(1).attributes).to eq(model_class.data.select{|e| e[:id] == 1}.first) + end + + context 'when data ordered' do + before do + model_class.order(id: "DESC") + end + + it 'returns a correct record' do + expect(subject.find(1).attributes).to eq(model_class.data.select{|e| e[:id] == 1}.first) + end + end + end end