Permalink
Browse files

Re-implement instance methods previous and next

  • Loading branch information...
1 parent 9e76095 commit 06ae9ac7d40210d01e7241e45a6ddede9bf43cf2 @radar committed Feb 20, 2012
Showing with 43 additions and 2 deletions.
  1. +3 −0 lib/by_star.rb
  2. +13 −0 lib/by_star/instance_methods.rb
  3. +27 −2 spec/by_star/by_direction_spec.rb
View
3 lib/by_star.rb
@@ -1,6 +1,7 @@
require 'chronic'
require 'by_star/time_ext'
+require 'by_star/instance_methods'
require 'by_star/by_direction'
require 'by_star/by_year'
@@ -58,3 +59,5 @@ def time_klass(time)
ActiveRecord::Base.send :extend, ByStar
ActiveRecord::Relation.send :extend, ByStar
+
+ActiveRecord::Base.send :include, ByStar::InstanceMethods
View
13 lib/by_star/instance_methods.rb
@@ -0,0 +1,13 @@
+module ByStar
+ module InstanceMethods
+ def previous(options={})
+ field = options[:field] || self.class.by_star_field
+ self.class.where("#{field} < ?", self.send(field)).order("#{field} DESC").first
+ end
+
+ def next(options={})
+ field = options[:field] || self.class.by_star_field
+ self.class.where("#{field} > ?", self.send(field)).order("#{field} ASC").first
+ end
+ end
+end
View
29 spec/by_star/by_direction_spec.rb
@@ -29,7 +29,7 @@ def posts_count(*args)
end
it "should be able to find all events before Ryan's birthday using a non-standard field" do
- Event.before(Time.local(Time.zone.now.year+2), :field => "start_time").count.should eql(9)
+ Event.before(Time.local(Time.zone.now.year+2), :field => "start_time").count.should eql(8)
end
end
@@ -52,6 +52,31 @@ def posts_count(*args)
end
it "should be able to find all events before Dad's birthday using a non-standard field" do
- Event.after(Time.zone.local(Time.zone.now.year, 7, 5), :field => "start_time").count.should eql(4)
+ Event.after(Time.zone.local(Time.zone.now.year, 7, 5), :field => "start_time").count.should eql(3)
+ end
+end
+
+describe "previous and next" do
+ let(:current_post) { Post.find_by_text("post 1") }
+ let(:current_event) { Event.find_by_name("Mum's Birthday!") }
+
+ context "previous" do
+ it "can find the previous post" do
+ current_post.previous.text.should == "Last year"
+ end
+
+ it "takes the field option" do
+ current_event.previous(:field => "start_time").name.should == "Dad's birthday!"
+ end
+ end
+
+ context "next" do
+ it "can find the next post" do
+ current_post.next.text.should == "The 'Current' Week"
+ end
+
+ it "takes the field option" do
+ current_event.next(:field => "start_time").name.should == "Ryan's birthday!"
+ end
end
end

0 comments on commit 06ae9ac

Please sign in to comment.