Skip to content

Instantly share code, notes, and snippets.

@nakajima
Created June 27, 2009 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakajima/136835 to your computer and use it in GitHub Desktop.
Save nakajima/136835 to your computer and use it in GitHub Desktop.
Here's an example refactoring from http://www.workingwithrails.com/forums/4-ask-a-rails-expert/topics/789-optimising-code
class Role < ActiveRecord::Base
ADMIN = 'admin'
belongs_to :user
belongs_to :building
named_scope :by, proc { |role|
{ :conditions => ['name = ?', role] }
}
end
class User < ActiveRecord::Base
has_many :roles
has_many :buildings, :through => :roles
end
# The new way...
class Building < ActiveRecord::Base
has_many :roles
has_many :users, :through => :roles do
# Association extension
def with_role(name)
scoped(:conditions => ['roles.name = ? AND roles.id = ?', name, proxy_owner.id])
end
end
def find_admins_of
users.with_role(Role::ADMIN)
end
end
# The old way...
class Building < ActiveRecord::Base
def find_admins_of
roles = self.roles
admins = []
for role in roles
admins << User.find(role.user_id) if role.role_type_id == Role::ADMIN
end
admins
end
end
require 'test/unit'
class AdminTest < Test::Unit::TestCase
def test_with_role_filters_by_role
# Create test objects
admin = User.create!
not_admin = User.create!
building = Building.create!
# Give the admin user the right role
admin.roles.create! :name => Role::ADMIN, :building => building
# Assert that the filter works
assert_equal [admin], building.users.with_role(Role::ADMIN)
# ...or if you prefer:
assert_equal [admin], building.find_admins_of
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment