Skip to content

Commit

Permalink
Implement User#<=> for easier sorting. [#18]
Browse files Browse the repository at this point in the history
  • Loading branch information
marnen committed Mar 24, 2009
1 parent 0fda006 commit 21e3b4d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 13 deletions.
32 changes: 19 additions & 13 deletions app/models/user.rb
Expand Up @@ -37,19 +37,6 @@ def country
return self.state.nil? ? nil : self.state.country
end

# Returns the user's name as a string. Order can be :first_last (default) or :last_first. E-mail address will be returned if no name is specified.
def to_s(format = :first_last)
case format
when :first_last
str = [self.firstname, self.lastname].delete_if {|e| e.blank?}.join(' ')
when :last_first
str = [self.lastname, self.firstname].delete_if {|e| e.blank?}.join(', ')
else
raise ArgumentError, "format must be :first_last, :last_first, or blank"
end
str.blank? ? self.email : str
end

def coords
c = self[:coords]
if c.nil?
Expand All @@ -67,6 +54,25 @@ def coords
end
c
end

# Compares users by last name, first name, and e-mail address in that order.
# ['Smith', 'John', 'jsmith1@aol.com'] < ['Smith', 'John', 'jsmith2@aol.com']
def <=>(other)
[self.lastname, self.firstname, self.email] <=> [other.lastname, other.firstname, other.email]
end

# Returns the user's name as a string. Order can be :first_last (default) or :last_first. E-mail address will be returned if no name is specified.
def to_s(format = :first_last)
case format
when :first_last
str = [self.firstname, self.lastname].delete_if {|e| e.blank?}.join(' ')
when :last_first
str = [self.lastname, self.firstname].delete_if {|e| e.blank?}.join(', ')
else
raise ArgumentError, "format must be :first_last, :last_first, or blank"
end
str.blank? ? self.email : str
end

##### The stuff below here comes from restful_authentication.

Expand Down
19 changes: 19 additions & 0 deletions spec/models/user_spec.rb
Expand Up @@ -110,6 +110,25 @@
describe User, "(instance properties)" do
fixtures :users

describe "<=>" do
it "should be valid" do
User.new.should respond_to(:<=>)
User.method(:<=>).arity.should == 1
end

it "should sort on last name, first name, and e-mail address in that order" do
smith = u(['Smith', 'John', 'jsmith1@aol.com'])
(smith <=> u(['Smith', 'John', 'jsmith2@aol.com'])).should == -1
(smith <=> u(['Jones', 'Robert', 'rj123@gmail.com'])).should == 1
(smith <=> u(['Smith', 'Mary', 'aaa@aaa.com'])).should == -1
end

protected
def u(array)
User.new(:lastname => array[0], :firstname => array[1], :email => array[2])
end
end

describe "to_s" do
it "should return firstname or lastname if only one of these is defined, 'firstname lastname' if both are defined, or e-mail address if no name is defined" do
@user = User.new
Expand Down

0 comments on commit 21e3b4d

Please sign in to comment.