]> source.dussan.org Git - redmine.git/commitdiff
Merged r11508 from trunk (#13301).
authorJean-Philippe Lang <jp_lang@yahoo.fr>
Fri, 1 Mar 2013 16:22:02 +0000 (16:22 +0000)
committerJean-Philippe Lang <jp_lang@yahoo.fr>
Fri, 1 Mar 2013 16:22:02 +0000 (16:22 +0000)
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.3-stable@11516 e93f8b46-1217-0410-a6f0-8f06a7374b81

app/models/user.rb
test/unit/user_test.rb

index 3670ad2a1dcb2dfa8b1eae20b59e0b79c8acfdbd..81c74e52acd293ad713fe92fd9fa6690d929c6d8 100644 (file)
@@ -131,6 +131,7 @@ class User < Principal
   def reload(*args)
     @name = nil
     @projects_by_role = nil
+    @membership_by_project_id = nil
     super
   end
 
@@ -415,6 +416,17 @@ class User < Principal
     !logged?
   end
 
+  # Returns user's membership for the given project
+  # or nil if the user is not a member of project
+  def membership(project)
+    project_id = project.is_a?(Project) ? project.id : project
+
+    @membership_by_project_id ||= Hash.new {|h, project_id|
+      h[project_id] = memberships.where(:project_id => project_id).first
+    }
+    @membership_by_project_id[project_id]
+  end
+
   # Return user's roles for project
   def roles_for_project(project)
     roles = []
@@ -422,7 +434,7 @@ class User < Principal
     return roles if project.nil? || project.archived?
     if logged?
       # Find project membership
-      membership = memberships.detect {|m| m.project_id == project.id}
+      membership = membership(project)
       if membership
         roles = membership.roles
       else
index 28d09518eb90d162d50c70606543aaaa8301b2a9..18a63703725ef8b7ab7bd873942bfa95cb27fffa 100644 (file)
@@ -727,6 +727,32 @@ class UserTest < ActiveSupport::TestCase
     assert_equal true, User.default_admin_account_changed?
   end
 
+  def test_membership_with_project_should_return_membership
+    project = Project.find(1)
+
+    membership = @jsmith.membership(project)
+    assert_kind_of Member, membership
+    assert_equal @jsmith, membership.user
+    assert_equal project, membership.project
+  end
+
+  def test_membership_with_project_id_should_return_membership
+    project = Project.find(1)
+
+    membership = @jsmith.membership(1)
+    assert_kind_of Member, membership
+    assert_equal @jsmith, membership.user
+    assert_equal project, membership.project
+  end
+
+  def test_membership_for_non_member_should_return_nil
+    project = Project.find(1)
+
+    user = User.generate!
+    membership = user.membership(1)
+    assert_nil membership
+  end
+
   def test_roles_for_project
     # user with a role
     roles = @jsmith.roles_for_project(Project.find(1))