Permalink
Browse files

Added sorted_by and made all sort by it. Defaults to id.

  • Loading branch information...
1 parent 8c8e207 commit 2f9f07c322e9f7316fb50b48cc50d3b8ecfcd0b7 @jnunemaker committed Dec 28, 2010
Showing with 39 additions and 9 deletions.
  1. +8 −4 lib/scam.rb
  2. +31 −5 spec/scam_spec.rb
View
@@ -2,14 +2,18 @@ module Scam
def self.included(base)
base.extend(ClassMethods)
base.class.send(:include, Enumerable)
- base.class_eval do
- attr_accessor(:id)
- end
+ base.class_eval { attr_accessor(:id) }
end
module ClassMethods
def all
- instances.sort_by { |i| i.id }
+ instances.sort_by { |i| i.send(sorted_by) }
+ end
+
+ def sorted_by(attribute=nil)
+ @sorted_by = attribute unless attribute.nil?
+ @sorted_by = :id if @sorted_by.nil?
+ @sorted_by
end
def create(attrs={})
View
@@ -20,14 +20,40 @@
end
end
+ describe ".sorted_by" do
+ it "defaults to id" do
+ FeedTemplate.sorted_by.should == :id
+ end
+
+ it "gets/sets sorted_by" do
+ FeedTemplate.sorted_by(:position)
+ FeedTemplate.sorted_by.should == :position
+ end
+ end
+
describe ".all" do
- before do
- FeedTemplate.create(:id => 2)
- FeedTemplate.create(:id => 1)
+ context "default sort by" do
+ before do
+ FeedTemplate.create(:id => 2)
+ FeedTemplate.create(:id => 1)
+ end
+
+ it "returns all instances sorted by id" do
+ FeedTemplate.all.map(&:id).should == [1, 2]
+ end
end
- it "returns all instances sorted by id" do
- FeedTemplate.all.map(&:id).should == [1, 2]
+ context "custom sort by" do
+ before do
+ FeedTemplate.sorted_by(:position)
+ FeedTemplate.send(:attr_accessor, :position)
+ FeedTemplate.create(:id => 2, :position => 1)
+ FeedTemplate.create(:id => 1, :position => 2)
+ end
+
+ it "returns all instances sorted by custom attribute" do
+ FeedTemplate.all.map(&:id).should == [2, 1]
+ end
end
end

0 comments on commit 2f9f07c

Please sign in to comment.