From f1e165d7df2c84a77a6a97ba92abb710270d6d8d Mon Sep 17 00:00:00 2001 From: Paul Sponagl Date: Fri, 6 Jan 2012 12:20:50 +0100 Subject: [PATCH] with_scope order_by: "fieldname [asc|desc]" --- app/models/content_type.rb | 33 +++++++++++++++++++++----------- spec/models/content_type_spec.rb | 7 +++++++ 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/app/models/content_type.rb b/app/models/content_type.rb index 978c804a..1023d8d3 100644 --- a/app/models/content_type.rb +++ b/app/models/content_type.rb @@ -83,28 +83,39 @@ class ContentType list = (if conditions.nil? || conditions.empty? self.contents else + # check for order_by: "field [asc|desc]" condition + if order_by = ( conditions.delete('order_by') || conditions.delete(:order_by) ) + column, sort_order = order_by.split + column = column.to_sym + else + sort_order = nil + end + conditions_with_names = {} conditions.each do |key, value| # convert alias (key) to name - field = self.content_custom_fields.detect { |f| f._alias == key } + if field = self.content_custom_fields.detect { |f| f._alias == key } - case field.kind.to_sym - when :category - if (category_item = field.category_items.where(:name => value).first).present? - conditions_with_names[field._name.to_sym] = category_item._id + case field.kind.to_sym + when :category + if (category_item = field.category_items.where(:name => value).first).present? + conditions_with_names[field._name.to_sym] = category_item._id + end + else + conditions_with_names[field._name.to_sym] = value end - else - conditions_with_names[field._name.to_sym] = value end end - self.contents.where(conditions_with_names) + conditions_with_names.blank? ? self.contents : self.contents.where(conditions_with_names) end).sort { |a, b| (a.send(column) && b.send(column)) ? (a.send(column) || 0) <=> (b.send(column) || 0) : 0 } - return list if self.order_manually? - - self.asc_order? ? list : list.reverse + if sort_order.nil? + (self.order_manually? || self.asc_order?) ? list : list.reverse + else + sort_order == 'asc' ? list : list.reverse + end end def sort_contents!(ids) diff --git a/spec/models/content_type_spec.rb b/spec/models/content_type_spec.rb index 0d487711..8f038958 100644 --- a/spec/models/content_type_spec.rb +++ b/spec/models/content_type_spec.rb @@ -89,6 +89,13 @@ describe ContentType do @content_type.order_direction = 'desc' @content_type.ordered_contents.collect(&:name).should == %w(Sacha Did) end + + it 'returns a list of contents ordered through condition {order_by: "name asc"}' do + @content_type.order_by = 'name' + @content_type.order_direction = 'desc' + @content_type.ordered_contents(:order_by => 'name asc').collect(&:name).should == %w(Did Sacha) + end + it 'returns a list of contents ordered by a Date column when first instance is missing the value' do @content_type = FactoryGirl.build(:content_type, :order_by => 'created_at')