diff --git a/app/models/content_instance.rb b/app/models/content_instance.rb index 0322ff86..527c76ba 100644 --- a/app/models/content_instance.rb +++ b/app/models/content_instance.rb @@ -50,6 +50,14 @@ class ContentInstance def visible? self._visible || self._visible.nil? end + + def next + content_type.contents.where(:_position_in_list => _position_in_list + 1).first() + end + + def previous + content_type.contents.where(:_position_in_list => _position_in_list - 1).first() + end def errors_to_hash Hash.new.replace(self.errors) diff --git a/lib/locomotive/liquid/drops/content.rb b/lib/locomotive/liquid/drops/content.rb index 1aefc759..2e3fcb37 100644 --- a/lib/locomotive/liquid/drops/content.rb +++ b/lib/locomotive/liquid/drops/content.rb @@ -8,6 +8,32 @@ module Locomotive def _id self._source._id.to_s end + + # Returns the next content for the parent content type. + # If no content is found, nil is returned. + # + # Usage: + # + # {% if article.next %} + # Read next article + # {% endif %} + # + def next + self._source.next.to_liquid + end + + # Returns the previous content for the parent content type. + # If no content is found, nil is returned. + # + # Usage: + # + # {% if article.previous %} + # Read previous article + # {% endif %} + # + def previous + self._source.previous.to_liquid + end def before_method(meth) return '' if self._source.nil? diff --git a/spec/models/content_instance_spec.rb b/spec/models/content_instance_spec.rb index f34e2957..ef49fcd5 100644 --- a/spec/models/content_instance_spec.rb +++ b/spec/models/content_instance_spec.rb @@ -41,6 +41,35 @@ describe ContentInstance do end end + + describe "#navigation" do + before(:each) do + %w(first second third).each_with_index do |item,index| + content = build_content({:title => item.to_s}) + content._position_in_list = index + instance_variable_set "@#{item}", content + end + end + + it 'should find previous item when available' do + puts @second.previous + @second.previous.custom_field_1.should == "first" + @second.previous._position_in_list.should == 0 + end + + it 'should find next item when available' do + @second.next.custom_field_1.should == "third" + @second.next._position_in_list.should == 2 + end + + it 'should return nil when fetching previous item on first in list' do + @first.previous.should == nil + end + + it 'should return nil when fetching next item on last in list' do + @third.next.should == nil + end + end describe '#permalink' do