lib/ohm.rb in ohm-0.0.16 vs lib/ohm.rb in ohm-0.0.17
- old
+ new
@@ -82,18 +82,36 @@
options[:start] ||= 0
options[:limit] = [options[:start], options[:limit]] if options[:limit]
instantiate(db.sort(key, options))
end
- # Sort the model instances by the given value.
+ # Sort the model instances by the given attribute.
+ #
+ # @example Sorting elements by name:
+ #
+ # User.create :name => "B"
+ # User.create :name => "A"
+ #
+ # user = User.all.sort_by :name, :order => "ALPHA"
+ # user.name == "A" #=> true
def sort_by(att, options = {})
sort(options.merge(:by => model.key("*", att)))
end
+ # Sort the model instances by id and return the first instance
+ # found. If a :by option is provided with a valid attribute name, the
+ # method sort_by is used instead and the option provided is passed as the
+ # first parameter.
+ #
+ # @see #sort
+ # @see #sort_by
# @return [Ohm::Model, nil] Returns the first instance found or nil.
- def first
- sort(:limit => 1).first
+ def first(options = {})
+ options = options.merge(:limit => 1)
+ options[:by] ?
+ sort_by(options.delete(:by), options).first :
+ sort(options).first
end
def to_ary
all
end
@@ -170,12 +188,12 @@
# end
#
# company = Company.create :name => "Redis Co."
# company.employees << "Albert"
# company.employees << "Benoit"
- # company.employees.all #=> ["Albert", "Benoit"]
- # company.include?("Albert") #=> true
+ # company.employees.all #=> ["Albert", "Benoit"]
+ # company.include?("Albert") #=> true
class Set < Collection
# @param value [#to_s] Adds value to the list.
def << value
db.sadd(key, value)
@@ -384,10 +402,10 @@
add_to_indices
save!
end
def save
- create if new?
+ return create if new?
return unless valid?
update_indices
save!
end