Merge pull request #208 from karlbright/next_previous_content

Provide next and previous methods for content
This commit is contained in:
Mario Visic 2011-09-15 21:04:22 -07:00
commit ca2ad98cd0
3 changed files with 63 additions and 0 deletions

View File

@ -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)

View File

@ -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 %}
# <a href="/articles/{{ article.next._permalink }}">Read next article</a>
# {% 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 %}
# <a href="/articles/{{ article.previous._permalink }}">Read previous article</a>
# {% endif %}
#
def previous
self._source.previous.to_liquid
end
def before_method(meth)
return '' if self._source.nil?

View File

@ -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