lib/mongoid/orderable.rb in mongoid_orderable-4.0.0 vs lib/mongoid/orderable.rb in mongoid_orderable-4.1.0
- old
+ new
@@ -9,12 +9,22 @@
:scope => nil,
:base => 1
}
configuration.merge! options if options.is_a?(Hash)
- configuration[:scope] = "#{configuration[:scope]}_id".to_sym if configuration[:scope].is_a?(Symbol) && configuration[:scope].to_s !~ /_id$/
+ if configuration[:scope].is_a?(Symbol) && configuration[:scope].to_s !~ /_id$/
+ scope_relation = self.relations[configuration[:scope].to_s]
+ if scope_relation
+ configuration[:scope] = scope_relation.key.to_sym
+ else
+ configuration[:scope] = "#{configuration[:scope]}_id".to_sym
+ end
+ elsif configuration[:scope].is_a?(String)
+ configuration[:scope] = configuration[:scope].to_sym
+ end
+
field configuration[:column], orderable_field_opts(configuration)
if configuration[:index]
if MongoidOrderable.mongoid2?
index configuration[:column]
else
@@ -56,10 +66,46 @@
field_opts.merge!(configuration.slice(:as))
field_opts
end
end
+ ##
+ # Returns items above the current document.
+ # Items with a position lower than this document's position.
+ def previous_items
+ orderable_scoped.where(orderable_column.lt => self.position)
+ end
+ alias_method :prev_items, :previous_items
+
+ ##
+ # Returns items below the current document.
+ # Items with a position greater than this document's position.
+ def next_items
+ orderable_scoped.where(orderable_column.gt => self.position)
+ end
+
+ # returns the previous item in the list
+ def previous_item
+ if previous_items.present?
+ previous_position = self.position - 1
+ orderable_scoped.where(:position => previous_position).first
+ else
+ nil
+ end
+ end
+ alias_method :prev_item, :previous_item
+
+ # returns the next item in the list
+ def next_item
+ if next_items.present?
+ next_position = self.position + 1
+ orderable_scoped.where(:position => next_position).first
+ else
+ nil
+ end
+ end
+
def move_to! target_position
@move_to = target_position
save
end
alias_method :insert_at!, :move_to!
@@ -124,10 +170,10 @@
send "#{orderable_column}=", value
end
def orderable_scoped
if embedded?
- send(metadata.inverse).send(metadata.name).orderable_scope(self)
+ send(MongoidOrderable.metadata(self).inverse).send(MongoidOrderable.metadata(self).name).orderable_scope(self)
else
(orderable_inherited_class || self.class).orderable_scope(self)
end
end