Skip to content

Commit

Permalink
Make nil-safe and case-insensitive. [#18]
Browse files Browse the repository at this point in the history
  • Loading branch information
marnen committed Mar 24, 2009
1 parent f767868 commit ffd7927
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 3 deletions.
3 changes: 1 addition & 2 deletions app/models/user.rb
Expand Up @@ -59,8 +59,7 @@ def coords
# ['Smith', 'John', 'jsmith1@aol.com'] < ['Smith', 'John', 'jsmith2@aol.com']
def <=>(other)
attrs = [:lastname, :firstname, :email]
attrs.collect{|a| self.read_attribute a} <=> attrs.collect{|a| other.read_attribute a}
#[self.lastname, self.firstname, self.email] <=> [other.lastname, other.firstname, other.email]
attrs.collect{|a| self[a].downcase rescue nil}.compact <=> attrs.collect{|a| other[a].downcase rescue nil}.compact
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.
Expand Down
5 changes: 4 additions & 1 deletion spec/models/user_spec.rb
Expand Up @@ -117,10 +117,13 @@
end

it "should sort on last name, first name, and e-mail address in that order" do
smith = u(['Smith', 'John', 'jsmith1@aol.com'])
attrs = ['Smith', 'John', 'jsmith1@aol.com']
smith = u(attrs)
(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
(smith <=> u([nil, nil, 'Smitty@aol.com'])).should == -1 # nil-safe
(smith <=> u(attrs.collect(&:downcase))).should == 0 # not case-sensitive
end

protected
Expand Down

0 comments on commit ffd7927

Please sign in to comment.