fix issue about the order_by method of the MongoDB adapter (issue locomotivecms/engine#1119)
did
committed Feb 15, 2016
commit 56ffc0894c06ef8b5220322899e99ed3b2547b46
Showing 3
changed files with
55 additions
and 2 deletions
locomotive/steam/adapters/mongodb/query.rb b/lib/locomotive/steam/adapters/mongodb/query.rb
+20
-1
| @@ | @@ -25,7 +25,7 @@ module Locomotive::Steam |
| def order_by(*args) | |
| self.tap do | |
| - | @sort = [*args] |
| + | @sort = decode_order_by(*args) |
| end | |
| end | |
| @@ | @@ -100,6 +100,25 @@ module Locomotive::Steam |
| end | |
| end | |
| + | def decode_order_by(*spec) |
| + | [*spec].compact.map do |arg| |
| + | _decode_order_by(arg) |
| + | end |
| + | end |
| + | |
| + | def _decode_order_by(arg) |
| + | case arg |
| + | when String |
| + | if arg.include?(',') |
| + | _decode_order_by(arg.split(',')) |
| + | else |
| + | arg.strip.split(/[\s|.]/) |
| + | end |
| + | when Array then arg.map { |_arg| _decode_order_by(_arg) } |
| + | else arg |
| + | end |
| + | end |
| + | |
| end | |
| end | |
spec/integration/repositories/content_entry_repository_spec.rb
+10
-0
| @@ | @@ -61,6 +61,16 @@ describe Locomotive::Steam::ContentEntryRepository do |
| it { expect(subject.map { |h| h[:entries].size }).to eq([2, 1, 0]) } | |
| end | |
| + | describe '#order_by' do |
| + | let(:order_by) { 'name' } |
| + | subject { repository.all(order_by: order_by) } |
| + | it { expect(subject.map { |h| h[:name] }).to eq(['Alice in Chains', 'Pearl Jam', 'The who']) } |
| + | context 'a field and a direction' do |
| + | let(:order_by) { 'name.desc, leader asc' } |
| + | it { expect(subject.map { |h| h[:name] }).to eq(['The who', 'Pearl Jam', 'Alice in Chains']) } |
| + | end |
| + | end |
| + | |
| describe '#create' do | |
| let(:type) { type_repository.by_slug('songs') } | |
query_spec.rb b/spec/unit/adapters/mongodb/query_spec.rb
+25
-1
| @@ | @@ -40,7 +40,31 @@ describe Locomotive::Steam::Adapters::MongoDB::Query do |
| describe '#order_by' do | |
| - | it { expect(query.order_by(title: :asc, published: :desc).sort).to eq [{title: :asc, published: :desc}] } |
| + | subject { query.order_by(order_by).sort } |
| + | |
| + | context 'passing a hash' do |
| + | |
| + | let(:order_by) { { title: :asc, published: :desc } } |
| + | |
| + | it { is_expected.to eq [{title: :asc, published: :desc}] } |
| + | |
| + | end |
| + | |
| + | context 'passing an array of strings' do |
| + | |
| + | let(:order_by) { ['title.asc', 'published'] } |
| + | |
| + | it { is_expected.to eq [[['title', 'asc'], ['published']]] } |
| + | |
| + | end |
| + | |
| + | context 'passing a string' do |
| + | |
| + | let(:order_by) { 'title.asc, published' } |
| + | |
| + | it { is_expected.to eq [[['title', 'asc'], ['published']]] } |
| + | |
| + | end |
| end | |