Created
October 24, 2014 15:37
-
-
Save janlimpens/81b70a45484f83765603 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Portfolio | |
require 'slug' | |
include Mongoid::Document | |
include Mongoid::Slug | |
include ComparableByIndex | |
include CanBePublished | |
field :title, type: String | |
slug :title, history: true | |
field :description, type: String | |
embeds_many :portfolio_items, cascade_callbacks: true | |
validates_presence_of :title | |
#Mongoid::Slug does not yet set these: | |
index({'portfolio_items._slugs' => 1}, {unique: true}) | |
index({'portfolio_items.images._slugs' => 1}, {unique: true}) | |
before_save :apply_indices | |
def get_item_index(item) | |
return nil if item.nil? | |
portfolio_items.published.sorted.entries.index { |x| x.id == item.id } | |
end | |
def next_item(item) | |
index = get_item_index(item) | |
return nil if index.nil? | |
(index + 1) == portfolio_items.published.count ? nil : portfolio_items.published.sorted.entries[index + 1] | |
end | |
def previous_item(item) | |
index = get_item_index(item) | |
return nil if index.nil? | |
index == 0 ? nil : portfolio_items.published.sorted[index - 1] | |
end | |
private | |
def apply_indices | |
new_items = portfolio_items.where(index: -1) | |
count = portfolio_items.count | |
new_items.each do |item| | |
item.index = count | |
count = count + 1 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment