diff --git a/app/models/user.rb b/app/models/user.rb index 0acfdad6..a8f86193 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -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? @@ -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. diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 1a5681b2..c0de2613 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -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